排名前N的记录和按其他列分组

时间:2015-02-18 06:59:49

标签: sql-server sql-server-2008

我在SQL SERVER中有3列的表 Team (VARCHAR)Player (VARCHAR)Point (int) 有15支独特的球队,每支球队有20多名球员,每位球员都有一分。

我想根据他所有观点的总和得到每支球队的前十名球员(因为,每个球员可能有多排他得分的不同点)。

我试过,

SELECT TOP 10 Team,Player, 
   ISNULL(SUM([Point]), 0) 
   FROM [SportsTable] 
GROUP BY Teams, Player 
ORDER BY 3 DESC

但全球只有前十名球员(仅10排)。每个团队需要15 * 10 = 150行。

请告知。

1 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBER() OVER(PARTITION BY Team ORDER BY SUM(Point) DESC)

SELECT
    Team,
    Player,
    Point
FROM(
    SELECT
        Team,
        Player,
        Point = ISNULL(SUM(Point), 0),
        RN = ROW_NUMBER() OVER(PARTITION BY Team ORDER BY ISNULL(SUM(Point), 0) DESC)
    FROM SportsTable
    GROUP BY Team, Player
)t
WHERE RN <= 10