具有前 X 行总和的子查询

Subquery with Sum of top X rows

我正在尝试从 table 中获取每个人的前 5 个结果。我能够为他们获得最高结果,但我想要前 5 名的总和。

Select Distinct
        r.LastName, 
        r.FirstName , 
        r.Class,
        r.BibNum,
        (Select top 1 r2.points from Results r2 where r2.season=r.Season and r2.Mountain=r.Mountain and r2.Bibnum=r.bibnum Order By r2.Points Desc) as Points
from Results as r Where Season='2015' and Mountain='Ski Resort'
Order By Class, Points Desc

列:

    [Id] [int] IDENTITY(1,1) NOT NULL,
    [RaceNum] [int] NOT NULL,
    [BibNum] [int] NOT NULL,
    [FirstName] [nvarchar](max) NULL,
    [LastName] [nvarchar](max) NULL,
    [Sex] [nvarchar](max) NULL,
    [Class] [nvarchar](max) NULL,
    [Team] [nvarchar](max) NULL,
    [FirstRun] [nvarchar](max) NULL,
    [SecondRun] [nvarchar](max) NULL,
    [Best] [nvarchar](max) NULL,
    [Points] [int] NOT NULL,
    [Season] [int] NOT NULL,
    [Mountain] [nvarchar](max) NULL

您可以使用 row_number() 获取前五行,然后按其他字段分组:

SELECT   LastName, 
         FirstName, 
         Class,
         BibNum,
         SUM(points) 
FROM     (SELECT  LastName, 
                  FirstName, 
                  Class,
                  BibNum,
                  points,
                  ROW_NUMBER() OVER (PARTITION BY LastName, 
                                                  FirstName, 
                                                  Class,
                                                  BibNum
                                     ORDER BY points DESC) AS rn
           FROM   results
           WHERE  Season='2015' and Mountain='Ski Resort'
         ) t
WHERE    rn <= 5
GROUP BY LastName, FirstName, Class, BibNum