SQL - SUM,Distinct和TOP 4

时间:2017-05-16 19:03:32

标签: sql sql-server

我查询了一个无法工作的表格。

以下是表格示例;

成员

|ID|NAME|
|1 |John|
|2 |Joe |
|3 |Paul|

得分

|ID  |Score |                       
|1   | 25   |                       
|1   | 34   |                       
|2   | 54   |                       
|1   | 23   |                       
|3   | 43   |                     
|2   | 14   |                       
|1   | 23   |                       
|3   | 43   |                     
|3   | 14   |                                             
|3   | 43   |                     
|2   | 14   |                       
|1   | 23   |                       
|3   | 43   |                     
|3   | 14   | 

我想显示成员名称,然后在那里得出最好的2个分数,并首先显示最大的SUM'd分数。

|Paul| 86 |
|Joe | 68 |
|John| 57 |

提前致谢

3 个答案:

答案 0 :(得分:5)

您可以使用row_number窗口函数来获得每个ID的TOP 2分数,然后使用group by求和,最后加入MEMBERS表,例如:

select MEMBERS.name, tt.s from MEMBERS
inner join (
    select  ID, sum(Score) s from (
        select ID, Score, row_number() over(partition by ID order by Score desc) rn from SCORES
    ) t
    where rn <= 2
    group by id
)tt
on MEMBERS.id = tt.id
ORDER BY tt.s

答案 1 :(得分:0)

您可以使用group by子句和子选择

SELECT    M.NAME
          ,(SELECT SUM(S2.SCORE) 
           FROM   (SELECT TOP 2 S1.Score FROM SCORES S1
                   WHERE S1.ID = S.ID
                   ORDER BY S1.Score DESC) AS S2
           ) AS Two_Highest_Scores
FROM      SCORES S
LEFT JOIN MEMBERS M
       ON M.ID = S.ID
GROUP BY  M.ID
          ,M.NAME

你可以测试一下吗?

答案 2 :(得分:0)

尝试此查询(需要SQL Server 2012+)

SELECT name, best_score
FROM
(
    SELECT id, score
        , SUM(score) OVER (PARTITION BY id ORDER BY score DESC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS best_score
        , ROW_NUMBER() OVER (PARTITION BY id ORDER BY score DESC) AS row_num
    FROM Scores
) AS t
INNER JOIN Members AS m ON (m.id = t.id AND t.row_num = 1) 
ORDER BY best_score DESC;

首先,对于每个id,分数按降序排序。

(PARTITION BY id ORDER BY score DESC)

然后 SUM()用于当前行的得分以及 ROWS 子句

的后续1行
ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING

因此内部查询返回每行2个分数的总和。然后第一行编号用于获取best_score的行。也可以使用 GROUP BY