0

使用以下代码:

    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”。我错过了什么?

谢谢。

4

1 回答 1

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]
于 2016-03-01T17:01:55.780 回答