0

I want SQL to calculate number of work days between 2 dates. for example, the start date is 3/1/2017 and end date is 3/10/2017, so the result should be 8 days not 10 days. how to achieve that in SQL server. thanks

user2575502
  • 703
  • 12
  • 28

2 Answers2

0

If you want to show the days which are not in saturday and sunday within a date range. Then,

Query

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**

Community
  • 1
  • 1
Ullas
  • 11,450
  • 4
  • 33
  • 50
0

You can try this Query:

;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
Dmitry Cat
  • 475
  • 3
  • 11