sql server - Selecting SUM of TOP 2 values within a table with multiple GROUP in SQL -
i've been playing sets in sql server 2000 , have following table structure 1 of temp tables (#periods):
restctr hoursctr duration rest ---------------------------------------- 1 337 2 0 2 337 46 1 3 337 2 0 4 337 46 1 5 338 1 0 6 338 46 1 7 338 2 0 8 338 46 1 9 338 1 0 10 339 46 1 ...
what i'd calculate sum of 2 longest rest periods each hoursctr, preferably using sets , temp tables (rather cursors, or nested subqueries).
here's dream query won't work in sql (no matter how many times run it):
select hoursctr, sum ( top 2 duration ) longestbreaks #periods rest = 1 group hoursctr
the hoursctr can have number of rest periods (including none).
my current solution not elegant , involves following steps:
- get max duration of rest, group hoursctr
- select first (min) restctr row returns max duration each hoursctr
- repeat step 1 (excluding rows collected in step 2)
- repeat step 2 (again, excluding rows collected in step 2)
- combine restctr rows (from step 2 , 4) single table
- get sum of duration pointed rows in step 5, grouped hoursctr
if there set functions cut process down, welcome.
the best way in sql server common table expression, numbering rows in each group windowing function row_number()
:
with numberedperiods ( select hoursctr, duration, row_number() on (partition hoursctr order duration desc) rn #periods rest = 1 ) select hoursctr, sum(duration) longestbreaks numberedperiods rn <= 2 group hoursctr
edit: i've added order clause in partitioning, 2 longest rests.
mea culpa, did not notice need work in microsoft sql server 2000. version doesn't support cte's or windowing functions. i'll leave answer above in case helps else.
in sql server 2000, common advice use correlated subquery:
select p1.hoursctr, (select sum(t.duration) (select top 2 p2.duration #periods p2 p2.hoursctr = p1.hoursctr order p2.duration desc) t) longestbreaks #periods p1
Comments
Post a Comment