如果我今天(2012年8月21日)运行查询,我想得到这个结果集:
[...]
为了得到这个,我使用以下但似乎过于复杂。这可以简化吗?
;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
答案 0 :(得分:4)
你可以这样做:
select (number/7)+1 as multiple ,
number+1 as number,
dateadd(dd,-(182-number),GETDATE()) as EquivDates
from master..spt_values
where type='P'
and number<182
答案 1 :(得分:2)
我明白了:
select distinct
number,
[week] = ((number-1) / 7)+1,
olddate = DATEADD(DD,
-1 * (182-number+1),
DATEADD(dd,0,(DATEDIFF(dd,0,GETDATE()))))
from master..spt_values
where number between 1 and 182