如何计算sql Server 2008中表(从第1行到结尾)的两个日期之间的工作天数?
我试过这样的东西,但它不起作用
DECLARE @StartDate as DATETIME,@EndDate as DATETIME Select @StartDate = date2 from testtable ; select @EndDate = date1 from testtable ; SELECT (DATEDIFF(dd,@StartDate,@EndDate) + 1) -(DATEDIFF(wk,@EndDate) * 2) -(CASE WHEN DATENAME(dw,@StartDate) = 'Sunday' THEN 1 ELSE 0 END) -(CASE WHEN DATENAME(dw,@EndDate) = 'Saturday' THEN 1 ELSE 0 END)
解决方法
我会一直推荐
Calendar table,那么你可以简单地使用:
SELECT COUNT(*) FROM dbo.CalendarTable WHERE IsWorkingDay = 1 AND [Date] > @StartDate AND [Date] <= @EndDate;
由于sql不了解国定假日,例如两个日期之间的工作日数并不总是代表工作日数.这就是大多数数据库必须使用日历表的原因.它们不占用大量内存并简化了大量查询.
但如果这不是一个选项,那么你可以在运行中相对容易地生成一个日期表并使用它
SET DATEFIRST 1; DECLARE @StartDate DATETIME = '20131103',@EndDate DATETIME = '20131104'; -- GENERATE A LIST OF ALL DATES BETWEEN THE START DATE AND THE END DATE WITH AllDates AS ( SELECT TOP (DATEDIFF(DAY,@EndDate)) D = DATEADD(DAY,ROW_NUMBER() OVER(ORDER BY a.Object_ID),@StartDate) FROM sys.all_objects a CROSS JOIN sys.all_objects b ) SELECT WeekDays = COUNT(*) FROM AllDates WHERE DATEPART(WEEKDAY,D) NOT IN (6,7);
编辑
如果您需要计算两个日期列之间的差异,您仍然可以使用您的日历表:
SELECT t.ID,t.Date1,t.Date2,WorkingDays = COUNT(c.DateKey) FROM TestTable t LEFT JOIN dbo.Calendar c ON c.DateKey >= t.Date1 AND c.DateKey < t.Date2 AND c.IsWorkingDay = 1 GROUP BY t.ID,t.Date2;