Я смог заставить это работать с парой CTE, некоторыми декартовыми объединениями и небольшой таблицей чисел в базе данных master:
WITH
TestData AS (
SELECT CAST('01 May 2011' AS DATETIME) AS StartDate,'C1' AS Channel, 02 AS COUNT
UNION
SELECT CAST('01 May 2011' AS DATETIME) AS StartDate,'C3' AS Channel, 01 AS COUNT
UNION
SELECT CAST('08 May 2011' AS DATETIME) AS StartDate,'C2' AS Channel, 03 AS COUNT
UNION
SELECT CAST('15 May 2011' AS DATETIME) AS StartDate,'C1' AS Channel, 01 AS COUNT
),
Data_CTE AS (
SELECT Channel, DATEADD(d, -(DATEPART(dw, startdate)+5), CAST(startdate AS DATE)) WeekCommencing, SUM(Count) AS Count
FROM TestData
GROUP BY DATEADD(d, -(DATEPART(dw, startdate)+5), CAST(startdate AS DATE)), Channel),
Sub_CTE AS (
SELECT Dates.RefWeek, Channels.Channel, ISNULL((SELECT Count FROM Data_CTE WHERE Channel = Channels.Channel AND WeekCommencing = Dates.RefWeek) , 0) AS [Count]
FROM
(SELECT DATEADD(day, number * 7, (SELECT MIN(WeekCommencing) FROM Data_CTE)) RefWeek
FROM ( SELECT DISTINCT
number
FROM master.dbo.spt_values
WHERE name IS NULL
) n
WHERE
DATEADD(day, number * 7, (SELECT MIN(WeekCommencing) FROM Data_CTE)) <= (SELECT MAX(WeekCommencing) FROM Data_CTE)) AS Dates,
(SELECT DISTINCT Channel FROM Data_CTE) AS Channels)
SELECT
RefWeek, Channel, ( SELECT SUM(Count) FROM Sub_CTE WHERE Channel = s.Channel AND RefWeek <= s.RefWeek)
FROM Sub_CTE s
ORDER BY s.Channel, s.RefWeek
Проблема в том, что это не очень понятно иЯ наверняка удивлюсь, что за чертовщина была у меня, когда я вернусь, чтобы посмотреть на нее позже :) - О, хорошо.