Selecting SUM of TOP 2 values within a table with multiple GROUP in SQL

后端 未结 3 568
难免孤独
难免孤独 2021-01-12 03:06

I\'ve been playing with sets in SQL Server 2000 and have the following table structure for one of my temp tables (#Periods):

    RestCTR     HoursCTR    Duration          


        
3条回答
  •  终归单人心
    2021-01-12 03:16

    The best way to do this in SQL Server is with a common table expression, numbering the rows in each group with the windowing function ROW_NUMBER():

    WITH NumberedPeriods AS (
      SELECT HoursCTR, Duration, ROW_NUMBER() 
        OVER (PARTITION BY HoursCTR ORDER BY Duration DESC) AS RN
      FROM #Periods
      WHERE Rest = 1
    )
    SELECT HoursCTR, SUM(Duration) AS LongestBreaks
    FROM NumberedPeriods
    WHERE RN <= 2
    GROUP BY HoursCTR
    

    edit: I've added an ORDER BY clause in the partitioning, to get the two longest rests.


    Mea culpa, I did not notice that you need this to work in Microsoft SQL Server 2000. That version doesn't support CTE's or windowing functions. I'll leave the answer above in case it helps someone else.

    In SQL Server 2000, the common advice is to use a correlated subquery:

    SELECT p1.HoursCTR, (SELECT SUM(t.Duration) FROM 
        (SELECT TOP 2 p2.Duration FROM #Periods AS p2
         WHERE p2.HoursCTR = p1.HoursCTR 
         ORDER BY p2.Duration DESC) AS t) AS LongestBreaks
    FROM #Periods AS p1
    

提交回复
热议问题