我有一个包含两列的表
start_date 03/09/2016 end_date 03/15/2016
现在我需要这两个日期之间的所有星期开始和结束日期
week_start_date week_end_date 03/07/2016 03/11/2016 03/14/2016 03/18/2016
如何使用sql查询实现此目的。没有程序或t-sql请。
答案 0 :(得分:0)
首先你必须找到@start_date和@end_date之间的所有日期:
declare @start_date datetime
declare @end_date datetime
set @start_date='03/09/2016'
set @end_date='03/15/2016'
;
WITH dates AS (
SELECT @start_date AS dt
UNION ALL
SELECT DATEADD(dd, 1, dt)
FROM dates s
WHERE DATEADD(dd, 1, dt) <= @end_date)
<强>结果:强>
2016-03-09 00:00:00.000
2016-03-10 00:00:00.000
2016-03-11 00:00:00.000
2016-03-12 00:00:00.000
2016-03-13 00:00:00.000
2016-03-14 00:00:00.000
2016-03-15 00:00:00.000
第二,你需要找工作日,'2'是星期一week_start_date
'6'是星期五week_end_date
select DATEPART(dw,'03/11/2016') -- friday =6
select DATEPART(dw,'03/14/2016') --- monday =2
这是最终查询:
declare @start_date datetime
declare @end_date datetime
set @start_date='03/01/2016'
set @end_date='03/31/2016'
;
WITH sample AS (
SELECT @start_date AS dt
UNION ALL
SELECT DATEADD(dd, 1, dt)
FROM sample s
WHERE DATEADD(dd, 1, dt) <= @end_date)
, dayofWeekTemp as(
SELECT Cast(DATEPART(dw,s.dt) as int) dayOfWeekValue , s.dt dateValue
FROM sample s)
select Case when dayOfWeekValue =6 then 'End of week' when dayOfWeekValue=2 then 'Start of week' End,dateValue from dayofWeekTemp
where dayOfWeekValue=2 Or dayOfWeekValue=6
<强>结果
End of week 2016-03-04 00:00:00.000
Start of week 2016-03-07 00:00:00.000
End of week 2016-03-11 00:00:00.000
Start of week 2016-03-14 00:00:00.000
End of week 2016-03-18 00:00:00.000
Start of week 2016-03-21 00:00:00.000
End of week 2016-03-25 00:00:00.000
Start of week 2016-03-28 00:00:00.000