尝试这个 :
SQL小提琴
查询:
with demo_cte as
( select DATEPART(wk,getdate()) CW,DATEPART(MM,getdate()) MO
, GETDATE() cur_date, DATEADD(MM,-2,getdate()) end_date
union all
select DATEPART(wk,cur_date-7) CW,DATEPART(MM,cur_date-7) MO
, cur_date -7 cur_date, end_date
from demo_cte
where cur_date>end_date
)
select * from demo_cte
结果:
| CW | MO | CUR_DATE | END_DATE |
-------------------------------------------------------------------------
| 24 | 6 | June, 13 2013 12:18:43+0000 | April, 13 2013 12:18:43+0000 |
| 23 | 6 | June, 06 2013 12:18:43+0000 | April, 13 2013 12:18:43+0000 |
| 22 | 5 | May, 30 2013 12:18:43+0000 | April, 13 2013 12:18:43+0000 |
| 21 | 5 | May, 23 2013 12:18:43+0000 | April, 13 2013 12:18:43+0000 |
| 20 | 5 | May, 16 2013 12:18:43+0000 | April, 13 2013 12:18:43+0000 |
| 19 | 5 | May, 09 2013 12:18:43+0000 | April, 13 2013 12:18:43+0000 |
| 18 | 5 | May, 02 2013 12:18:43+0000 | April, 13 2013 12:18:43+0000 |
| 17 | 4 | April, 25 2013 12:18:43+0000 | April, 13 2013 12:18:43+0000 |
| 16 | 4 | April, 18 2013 12:18:43+0000 | April, 13 2013 12:18:43+0000 |
| 15 | 4 | April, 11 2013 12:18:43+0000 | April, 13 2013 12:18:43+0000 |
更新 :
尝试这个 :
Select * from test
where period like 'CW%' and
(CONVERT(tinyint, SUBSTRING(Period, 4, 2)) >= DATEPART(week, GETDATE()) - 5)
UNION
Select * from test
where period like 'MO%' and
(CONVERT(tinyint, SUBSTRING(Period, 4, 2)) >= DATEPART(MM, GETDATE()) - 2);
或这个
Select * from test
where (period like 'CW%' and
(CONVERT(tinyint, SUBSTRING(Period, 4, 2)) >= DATEPART(week, GETDATE()) - 5))
or
(period like 'MO%' and
(CONVERT(tinyint, SUBSTRING(Period, 4, 2)) >= DATEPART(MM, GETDATE()) - 2));