If I run the query today (21 Aug 2012) I want to get this result set:
[...]
To get this I'm using the following but it seems over-complicated. Can this be simplified?
;WITH Numbers_cte([number])
AS
( --return the numbers from 1 to 182 i.e 26*7
SELECT DISTINCT number
FROM Master..spt_values
WHERE number BETWEEN 1 AND 182
)
,MultipleSeven_cte([number], [multiple])
AS
( --divide the number series by 7 and return integers
SELECT
[number]
,[multiple] = (([number]-1) / 7)+1
FROM Numbers_cte
)
,Today_cte([Today])
AS
( --return the last date in the table or use GETDATE for this example
SELECT [Today]=CONVERT(DATETIME,CONVERT(CHAR(8),GETDATE()-1,112))
)
,EquivDates_cte([multiple],[number],[Today], [EquivDates])
AS
(
SELECT
x.multiple
,x.number
,y.Today
,[EquivDates] = DATEADD(DAY,-(182-x.number),y.[Today])
FROM MultipleSeven_cte x, Today_cte y
)
SELECT
multiple
,number
,[EquivDates]
FROM EquivDates_cte