You could create a permanent table with the weeks in it, and then just use the final query.
If you have a lot of data in the table, and an index on date_worked, and you will only process some of the rows from the data table, it would probably be worthwhile to add a WHERE clause to check date_worked for the range of dates to be processed. Let me know if that applies here.
Main Topics
Browse All Topics





by: ScottPletcherPosted on 2005-02-01 at 12:28:23ID: 13196858
DECLARE @weeks TABLE (weekNum TINYINT, weekStart SMALLDATETIME, weekEnd SMALLDATETIME)
DECLARE @weekNum TINYINT
DECLARE @weekStart SMALLDATETIME
DECLARE @weekEnd SMALLDATETIME
SET @weekNum = 1
SET @weekStart = '2005-01-01'
SET @weekEnd = DATEADD(MINUTE, -1, DATEADD(DAY, 7, @weekStart))
WHILE @weakStart <= GETDATE()
BEGIN
INSERT INTO @weeks VALUES(@weekNum, @weekStart, @weekEnd)
SET @weekNum = @weekNum + 1
SET @weekStart = DATEADD(DAY, 7, @weekStart)
SET @weekEnd = DATEADD(DAY, 7, @weekEnd)
END --WHILE
SELECT key,
SUM(CASE WHEN weekNum = 1 THEN hours ELSE 0 END) AS [Week 1],
SUM(CASE WHEN weekNum = 2 THEN hours ELSE 0 END) AS [Week 2],
SUM(CASE WHEN weekNum = 3 THEN hours ELSE 0 END) AS [Week 3],
SUM(CASE WHEN weekNum = 4 THEN hours ELSE 0 END) AS [Week 4]
FROM data
INNER JOIN @weeks ON data.date_worked BETWEEN weekStart AND weekEnd
GROUP BY key