SQL:按唯一ID汇总最大N值

时间:2014-05-21 14:03:32

标签: sql-server-2005 group-by sum

我有一个填充了唯一ID和点

的表

我想在结果集中为每个不同的唯一ID加上最大的5个值。

例如:

我想要以下结果集......

UPN             Points
A308204201057   40
A308204201057   46
A308204201057   40
A308204201057   40
A308204201057   40
A308204201057   46
A308204201057   46
A308204201057   40
A308204201057   46
A308208401097   40
A308208401097   46
A308208401097   46
A308208401097   40
A308208401097   52
A308208401097   46
A308208401097   46
A308208401097   46
A881233002009   40
A881233002009   40
A881233002009   46
A881233002009   34
A881233002009   22
A881233002009   40
A881233002009   34
A881233002009   40
A881235002017   22
A881235002017   34
A881235002017   40
A881235002017   46
A881235002017   46
A881235002017   46
A881235002017   46
A881235002017   40

填充为...

UPN             Points
A308204201057   224
A308208401097   236
A881233002009   206
A881235002017   224

我可以按点降序排序并选择前5个值,我可以对UPN进行分组并将它们合计,但我无法弄清楚如何对UPN进行分组,但只能计算出5个最大值。

2 个答案:

答案 0 :(得分:1)

您可以使用CTE + ROW_NUMBER

WITH CTE AS
(
  SELECT UPN, Points, 
         RN = ROW_NUMBER() OVER (PARTITION BY UPN 
                                 ORDER BY Points DESC)
  FROM dbo.TableName
)
SELECT UPN, SumTop5Points = SUM(Points)
FROM CTE
WHERE RN <= 5
GROUP BY UPN
ORDER BY SumTop5Points DESC

Demo-Fiddle

结果:

UPN             SUMPOINTS
A308208401097   236
A308204201057   224
A881235002017   224
A881233002009   206

答案 1 :(得分:0)

类似下面的内容应该为你做的伎俩

WITH TableCTE AS(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY UPN ORDER BY Points) AS RowNumber,
       UPN,
       Points
    FROM    TABLENAME
 ) 

SELECT    UPN,
    SUM(Points)
FROM    TableCTE
WHERE    RowNumber <= 5
GROUP BY UPN;

查看此博客select top n rows from a table