我希望SQL计算两个日期之间的工作日数。例如,开始日期是3/1/2017,结束日期是2017年10月3日,因此结果应该是8天而不是10天。如何在SQL Server中实现。感谢
答案 0 :(得分:0)
如果您想显示星期六和星期日不在日期范围内的日期。然后,
<强>查询强>
declare @start as date = '2017-03-01';
declare @end as date = '2017-03-10';
declare @i as int = 0;
declare @j as int = datediff(day, @start, @end)
declare @t as table([date] date, [dayname] varchar(50));
while(@i <= @j)
begin
insert into @t([date], [dayname]) values
(dateadd(day, @i, @start), Datename(weekday, dateadd(day, @i, @start)));
set @i += 1;
end
select * from @t
where [dayname] not in('Saturday', 'Sunday');
<强> Demo Here 强>
答案 1 :(得分:0)
您可以尝试此查询:
;with work_days as (
-- CTE of work days
select 2 [day_of_week] union -- Monday
select 3 union -- Tuesday
select 4 union -- Wednesday
select 5 union -- Thursday
select 6 -- Friday
)
,dates_between as (
-- recursive CTE, for dates in range
select cast('20170301' as date) [day]
union all
select dateadd(day,1,[day]) from dates_between
where [day]=[day] and [day]<'20170310'
)
select *
from dates_between join work_days
on work_days.day_of_week = DATEPART(dw, dates_between.[day])
order by dates_between.[day]
OPTION (MAXRECURSION 0) -- if dates range more than 100 days