2017-03-06 89 views
0

我希望SQL計算兩個日期之間的工作天數。例如,開始日期爲2017年3月1日,結束日期爲2017年3月10日,因此結果應爲8天而不是10天。如何在SQL服務器中實現。謝謝想要一個SQL來計算兩個日期之間的工作天數

+0

你需要被考慮到國家法定節假日? –

+1

http://www.sqlservercentral.com/articles/Advanced+Querying/calculatingworkdays/1660/ –

+0

http://stackoverflow.com/questions/7388420/get-datediff-excluding-weekends-using-sql-server – Sam

回答

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

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 
相關問題