SQL:每个组中SUM的MAX

时间:2016-03-01 16:57:44

标签: sql-server group-by sum max partition-by

使用以下代码:

    SELECT [Section]
           ,[Subgroup]
           ,[ID]
           ,SUM([Amount]) AS [SUM]
    FROM Table
    GROUP BY [Section], [Subgroup], [ID]
    ORDER BY [Amount] DESC,[Section]

我能够产生以下内容:

Section Subgroup    ID  SUM
A   G   1   56787
A   G   2   45687
C   W   3   36746
C   W   4   27456
C   W   5   13546
C   G   6   9345
C   T   7   8535
A   G   8   8435
C   T   9   7245
A   G   11  7243
B   T   10  6245
B   T   12  5768
C   T   13  4676
A   G   14  3564
A   G   16  3465
C   T   15  2576
B   T   17  2478
A   S   18  1856
C   W   19  1567
B   T   20  1244
A   C   22  1146
C   T   21  1056
C   T   23  945
C   T   24  933
B   G   27  845
C   G   25  834
A   A   26  779
B   T   28  742
C   C   29  734
B   G   31  689
C   T   30  623
A   S   33  587
A   S   34  565
A   E   32  489
B   T   35  478
C   G   37  378
B   T   39  256

但我想得到的是每个部分中每个小组的最高金额:

Section Subgroup    ID  SUM
A   G   1   56787
A   S   18  1856
A   C   22  1146
A   A   26  779
A   E   32  489
B   T   10  6245
B   G   27  845
C   W   3   36746
C   G   6   9345
C   T   7   8535
C   C   29  734

我尝试过使用' OVER'和' PARTITION BY'但无法让他们工作。我调查了' RANK'太。我错过了什么?

感谢。

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT  [Section], [Subgroup], [ID], [SUM]
FROM (       
   SELECT [Section], [Subgroup], [ID], SUM([Amount]) AS [SUM],
          ROW_NUMBER() OVER (PARTITION BY [Section], [Subgroup] 
                             ORDER BY SUM([Amount]) DESC) As rn
   FROM Table
   GROUP BY [Section], [Subgroup], [ID]) AS t
WHERE t.rn = 1
ORDER BY [Section], [Subgroup]