Reputation: 7201
Below is my code to calculate the total amount of working days in the current month.
DECLARE @my int
DECLARE @myDeduct int
DECLARE @day INT
DECLARE @mydate DATETIME
SET @mydate = getDate()
SET @myDeduct = 0
SET DateFirst 1 -- Set it monday=1 (value)
--Saturday and Sunday on the first and last day of a month will Deduct 1
IF (DATEPART(weekday,(DATEADD(dd,-(DAY(@mydate)-1),@mydate))) > 5)
SET @myDeduct = @myDeduct + 1
IF (DATEPART(weekday,(DATEADD(dd,-(DAY(DATEADD(mm,1,@mydate))),
DATEADD(mm,1,@mydate)))) > 5)
SET @myDeduct = @myDeduct + 1
SET @my = day(DATEADD(dd,-(DAY(DATEADD(mm,1,@mydate))),DATEADD(mm,1,@mydate)))
select (((@my/7) * 5 + (@my%7)) - @myDeduct) as Working_Day_per_month
How can I now calculate how many of those working days are left for the current month? Not worried about public holidays.
Upvotes: 1
Views: 6327
Reputation: 7201
I used Joe G Joseph answer and altered it like this!
Declare @DaysLeft as INT
;With MyCTE AS
(
SELECT number + 1 as 'CurrentDay'
FROM master..spt_values
WHERE type='p'
AND number < datepart(dd, DateAdd(day,-1,DateAdd(Month,1,DateAdd(Month,
DateDiff(Month, 0, GETDATE()),0))))
AND datename(WEEKDAY,DateAdd(Month, DateDiff(Month, 0, GETDATE()),
number) ) not in ('Saturday','Sunday')
)
Select @DaysLeft = (Select COUNT(*) As MyTotal from MyCTE
WHERE CurrentDay >= DATEPART(DD, GETDATE()))
Select @DaysLeft
Upvotes: 1
Reputation: 24106
try this:
This Query will give you working days in the current month..Assuming non working days are Saturdays and Sundays. If you have a table which contains list of working days/holidays then you can join that table also with the query to get the correct result..
SELECT number+1 as 'day'
FROM master..spt_values
WHERE type='p'
AND number <datepart(dd, DateAdd(day,-1,DateAdd(Month,1,DateAdd(Month,
DateDiff(Month, 0, GETDATE()),0))))
AND datename(WEEKDAY,DateAdd(Month, DateDiff(Month, 0, GetDate()),
number) ) not in ('Saturday','Sunday')
Upvotes: 1