2012-09-18 49 views
1

以下是我計算當月工作天數的代碼。計算月份剩餘的總工作日數

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 

我現在該如何計算當月有多少工作日? 不擔心公共假期。

回答

1

試試這個:

此查詢會給你在當前month..Assuming非工作日工作日的週六和週日。如果你有一個包含工作日/假期,那麼你可以加入該表還與查詢,以獲得正確的結果列表的表..

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') 
+0

謝謝,請參閱我的答案,關於如何將它用於CTE – Etienne

1

我用喬摹瑟答案,並改變它像這樣!

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