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

后端 未结 3 602
难免孤独
难免孤独 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:21

    SQL 2000 does not have CTE's, nor ROW_NUMBER().
    Correlated subqueries can need an extra step when using group by.

    This should work for you:

    SELECT 
        F.HoursCTR,
        MAX (F.LongestBreaks) AS LongestBreaks -- Dummy max() so that groupby can be used.
    FROM
        (
            SELECT 
                Pm.HoursCTR, 
                (
                    SELECT 
                        COALESCE (SUM (S.Duration), 0)    
                    FROM 
                        (
                            SELECT TOP 2    T.Duration
                            FROM            #Periods    AS T
                            WHERE           T.HoursCTR  = Pm.HoursCTR 
                            AND             T.Rest      = 1
                            ORDER BY        T.Duration  DESC
                        ) AS S
                 ) AS LongestBreaks
            FROM
                #Periods AS Pm
        ) AS F
    GROUP BY
        F.HoursCTR
    

提交回复
热议问题