我正在试图弄清楚如何计算TSQL中两个日期之间“星期二”的数量?
“星期二”可以是任何价值。
答案 0 :(得分:12)
谢谢t-clausen.dk,保存了几天。 没有每天的实例:
declare @from datetime= '3/1/2013'
declare @to datetime = '3/31/2013'
select
datediff(day, -7, @to)/7-datediff(day, -6, @from)/7 AS MON,
datediff(day, -6, @to)/7-datediff(day, -5, @from)/7 AS TUE,
datediff(day, -5, @to)/7-datediff(day, -4, @from)/7 AS WED,
datediff(day, -4, @to)/7-datediff(day, -3, @from)/7 AS THU,
datediff(day, -3, @to)/7-datediff(day, -2, @from)/7 AS FRI,
datediff(day, -2, @to)/7-datediff(day, -1, @from)/7 AS SAT,
datediff(day, -1, @to)/7-datediff(day, 0, @from)/7 AS SUN
答案 1 :(得分:10)
declare @from datetime= '9/20/2011'
declare @to datetime = '9/28/2011'
select datediff(day, -6, @to)/7-datediff(day, -5, @from)/7
答案 2 :(得分:3)
@ t-clausen.dk& Andriy M回复t-clausen.dks response and comments
查询使用的事实是1900-01-01是星期一。并且1900-01-01是日期0.
select dateadd(day,0,0)
datediff
- 函数的第二个参数是startdate。
所以你要比较'1899-12-26'和你的@ to-date和'1899-12-26'是星期二
select datename(dw,dateadd(day, 0, -6)), datename(dw, '1899-12-26')
使用相同事实的第二个日期也是如此。
事实上,你可以与任何已知的星期二和相应的星期三进行比较(这不是你正在研究的日期间隔)。
declare @from datetime= '2011-09-19'
declare @to datetime = '2011-10-15'
select datediff(day, '2011-09-13', @to)/7-datediff(day, '2011-09-14', @from)/7 as [works]
,datediff(day, '2011-10-18', @to)/7-datediff(day, '2011-10-19', @from)/7 as [works too]
,datediff(day, '2011-09-27', @to)/7-datediff(day, '2011-09-28', @from)/7 as [dont work]
基本上算法是“所有星期二减去所有星期三”。
答案 3 :(得分:1)
查看此问题:Count work days between two dates
有几种方法可以为你的问题利用这个问题的答案。