如果我有2个日期,我知道我可以使用datediff计算两个日期之间的天数,小时数,分钟数等,例如:
declare @start datetime; set @start = '2013-06-14'; declare @end datetime; set @end = '2013-06-15'; select datediff( hour,@start,@end );
如何确定日期范围是否包含周末?
我想知道日期范围是否包含周末的原因是因为我想从日或小时数中减去周末.即如果开始日是星期五,结束日期是星期一,我应该只有1天或24小时.
Datepart 1 = Sunday,而datepart 7 = Saturday在我的服务器上.
解决方法
我有一个函数来计算两个日期之间的工作日,基本查询是
declare @start datetime; set @start = '2013-06-14'; declare @end datetime; set @end = '2013-06-17'; SELECT (DATEDIFF(dd,@Start,@end) +1) -- total number of days (inclusive) -(DATEDIFF(wk,@end) * 2) -- number of complete weekends in period -- remove partial weekend days,ie if starts on sunday or ends on saturday -(CASE WHEN DATENAME(dw,@Start) = 'Sunday' THEN 1 ELSE 0 END) -(CASE WHEN DATENAME(dw,@end) = 'Saturday' THEN 1 ELSE 0 END)
因此,如果日期包括周末,如果工作日与日期不同,则可以计算出来
SELECT case when (DATEDIFF(dd,@end) +1) <> (DATEDIFF(dd,@end) = 'Saturday' THEN 1 ELSE 0 END) then 'Yes' else 'No' end as IncludesWeekends
或者更简单
SELECT (DATEDIFF(wk,@end) * 2) +(CASE WHEN DATENAME(dw,@Start) = 'Sunday' THEN 1 ELSE 0 END) +(CASE WHEN DATENAME(dw,@end) = 'Saturday' THEN 1 ELSE 0 END) as weekendDays