試試這個:
SQL Fiddle
查詢:
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
Results:
| 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));
不知道這是否是我需要的。看到我上面添加的小提琴的結構。在那小提琴中我想過濾出「CW 08」-row。 – SvenB
@SvenB:過濾出「CW 08」是簡單的where子句。你可以添加樣本輸入和輸出。我將能夠提供幫助。 –
這只是一個例子。我知道我可以手動完成。例如,從現在起只有最後兩個月應該在一個stmt內工作。 – SvenB