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 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 like to do is to calculate the Sum of the 2 longest Rest periods for each HoursCTR, preferably using sets and temp tables (rather than cursors, or nested subqueries).
Here's the dream query that just won't work in SQL (no matter how many times I run it):
Select HoursCTR, SUM ( TOP 2 Duration ) as LongestBreaks
FROM #Periods
WHERE Rest = 1
Group By HoursCTR
The HoursCTR can have any number of Rest periods (including none).
My current solution is not very elegant and basically involves the following steps:
- Get the max duration of rest, group by HoursCTR
- Select the first (min) RestCTR row that returns this max duration for each HoursCTR
- Repeat step 1 (excluding the rows already collected in step 2)
- Repeat step 2 (again, excluding rows collected in step 2)
- Combine the RestCTR rows (from step 2 and 4) into single table
- Get SUM of the Duration pointed to by the rows in step 5, grouped by HoursCTR
If there are any set functions that cut this process down, they would be very welcome.