一尘不染

选择 TOP 3 最高分

sql

我有一个关于如何表达一些结果的输出的问题?问题是:在许多比赛中,参与者都进行了多次尝试。得分最高的尝试仅被考虑一次。编写查询以列出在每场比赛中排名前 3 的参赛者。如果多个参赛者在每场比赛中得分相同,则他们处于同一排名。

报告 event_id、排名 1 名称、排名 2 名称、排名 3 名称。通过 event_id 订购比赛。共享等级的名称应按字母顺序排列并用逗号分隔。

该数据库仅包含一个表:

event_id participant_name score
1434 Marcos 9.62821024209408
1434 Marcos 7.30471832966565
1434 Vitor 9.52821024209408
1434 Vitor 6.30471832966565

我的查询是:

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;
event_id participant_name score FinalRank
1434 Aurora Leedom 9.98 1
1434 Shaunta Barletta 9.88 2
1434 Tricia Norgard 9.85 3
2626 Annita Tessier 9.95 1
2626 Loura Fortino, 9.95 1
2626 Christinia Padgett 9.94 2
2626 Ashlyn Cheatam 9.72 3

所以我可以让结果排名,我的问题是我可以使用什么资源使结果看起来像这样:

event_id Rank 1 Rank 2 Rank 3
1434 Aurora Leedom Shaunta Barletta Tricia Norgard
2626 Annita Tessier, Loura Fortino Christinia Padgett Ashlyn Cheatam

任何帮助,将不胜感激!


阅读 100

收藏
2022-07-21

共1个答案

一尘不染

使用数据透视查询生成所需的 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;
2022-07-21