计算当月剩余的总工作日数

时间:2012-09-18 09:59:14

标签: sql sql-server tsql date

以下是我计算当月工作日总数的代码。

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

我现在如何计算当月有多少工作日? 不担心公众假期。

2 个答案:

答案 0 :(得分:1)

试试这个:

此查询将为您提供当月的工作日。假设非工作日是星期六和星期日。如果您有一个包含工作日/假日列表的表格,那么您也可以将该表格与查询一起加入以获得正确的结果。

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

答案 1 :(得分:1)

我使用了 Joe G Joseph 的答案,然后就这样改了!

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