[英]SQL User Defined Function to calculate the number of days between two dates
[英]Want a SQL to calculate number of work days between 2 dates
我希望SQL计算2个日期之间的工作日数。 例如,开始日期为3/1/2017,结束日期为3/10/2017,因此结果应为8天而不是10天。 如何在SQL Server中实现这一目标。 谢谢
如果要显示日期范围内不在周六和周日的日期。 然后,
询问
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');
您可以尝试以下查询:
;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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.