1

我试图从一张桌子上得到每个人的前 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
4

1 回答 1

2

您可以使用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
于 2015-03-07T14:26:41.627 回答