MAX的总和(TOP x)

时间:2011-03-13 01:43:49

标签: sql-server tsql

说我有一张如下表:

PK Code Value
1  A    200
2  A    300
3  A    25
4  A    75
5  A    50
6  A    15
7  A    300
8  A    75

我如何获得代码= A的前4个最高值的值(即只想要300 + 300 + 200 + 75的总和)

由于

1 个答案:

答案 0 :(得分:11)

您可以使用派生表或公用表表达式获得前4个SUM

SELECT SUM(Value) As Top4Sum
FROM
(
    SELECT TOP (4) Value
    FROM YourTable
    WHERE Code = 'A'
    ORDER BY Value DESC
) T

如果您希望每SUM TOP 4 Code,那么

;WITH CTE
     AS (SELECT *,
                ROW_NUMBER() OVER (PARTITION BY Code ORDER BY Value DESC) RN
         FROM   YourTable)
SELECT Code,
       SUM(Value)
FROM   CTE
WHERE  RN <= 4
GROUP  BY Code