我有一个关于如何表达一些结果的输出的问题?问题是:在许多比赛中,参与者都进行了多次尝试。得分最高的尝试仅被考虑一次。编写查询以列出在每场比赛中排名前 3 的参赛者。如果多个参赛者在每场比赛中得分相同,则他们处于同一排名。
报告 event_id、排名 1 名称、排名 2 名称、排名 3 名称。通过 event_id 订购比赛。共享等级的名称应按字母顺序排列并用逗号分隔。
该数据库仅包含一个表:
我的查询是:
WITH max_score AS ( SELECT event_id, participant_name, CAST(MAX(ROUND(score, 2,1)) AS DECIMAL (18,2)) AS score FROM scoretable GROUP BY event_id, participant_name ), Rank_table AS( SELECT event_id, participant_name, score, DENSE_RANK() OVER (PARTITION BY event_id ORDER BY score DESC) AS FinalRank FROM max_score ) SELECT * FROM Rank_table WHERE FinalRank <= 3 ORDER BY event_id, score DESC;
所以我可以让结果排名,我的问题是我可以使用什么资源使结果看起来像这样:
任何帮助,将不胜感激!
使用数据透视查询生成所需的 3 个输出列:
WITH cte AS ( SELECT *, DENSE_RANK() OVER (PARTITION BY event_id ORDER BY FinalRank) dr FROM Rank_table ) SELECT event_id, STRING_AGG(CASE WHEN dr = 1 THEN participant_name END, ',') WITHIN GROUP (ORDER BY participant_name) AS [Rank 1], STRING_AGG(CASE WHEN dr = 2 THEN participant_name END, ',') WITHIN GROUP (ORDER BY participant_name) AS [Rank 2], STRING_AGG(CASE WHEN dr = 3 THEN participant_name END, ',') WITHIN GROUP (ORDER BY participant_name) AS [Rank 3] FROM cte ORDER BY event_id;