在SQL Server中,这两个日期之间有多少8天的时间段?
@date1 = '2016/11/08'
@date2 = '2017/02/10'
手动我在这些日期之间有四个8天的时间段
答案 0 :(得分:1)
Declare @date1 date = '2016/11/08'
Declare @date2 date = '2017/02/10'
Select count(*)
From (
Select Top (DateDiff(DD,@date1,@date2)+1) D=cast(DateAdd(DD,Row_Number() Over (Order By (Select null))-1,@date1) as Date)
From master..spt_values n1, master..spt_values n2
) A
Where DatePart(DAY,D)=8
返回
4
答案 1 :(得分:0)
这是使用标准SQL Date函数的替代方法:
declare @StartDate datetime = '2016-11-08'
, @EndDate datetime = '2023-10-09' --'2017-02-10'
, @dayOfInterest int = 8 --in case you decided you were interested in a different date
--if you don't care whether or not start date is before or after end date; swap their values...
/*
select @StartDate = min(d)
, @EndDate = max(d)
from (select @StartDate d union select @EndDate) x
*/
select
case when @StartDate <= @EndDate then
--if the end date is after or on the start date, we count the number of eighths in between
datediff(month,@StartDate,@EndDate) --count the number of months between the two dates
+ case when datepart(dd,@StartDate)<=@dayOfInterest then 0 else -1 end --if our range excludes the nth this month, exclude it
+ case when datepart(dd,@EndDate)<@dayOfInterest then 0 else 1 end --if our range includes the nth on the last month, include it
else
0 --if the end date is before the start date; we return 0
end
CountTheDays --give the output column a name
<强>注意强>
注意:对于第8名,这将完美地运作。 对于28日之后的日期,这是不可靠的(你最好使用John Cappelletti's solution),因为我的逻辑将每月增加1天,无论那个月是否包含当天(即如果计算当天的数量)在1月1日到3月1日之间的30日,你得到2而不是1,因为我的逻辑假设2月30日是有效的日期。