SQL SERVER 2012中的NetWorkDays函数

时间:2016-08-08 11:36:09

标签: sql-server

sql server 2012中是否有一个只计算工作日的函数?

我一直在寻找但到目前为止没有运气。

谢谢!

3 个答案:

答案 0 :(得分:0)

不,SQL Server没有这样的功能,但您可以使用日历表:

DECLARE @date_start date = '2016-01-01',
        @date_end date = '2016-12-31';

WITH cte as (
SELECT @date_start as [d], 0 as Level
UNION ALL
SELECT DATEADD(day,1,[d]), [level] + 1 as [level]
from cte
WHERE [level] < DATEDIFF(day,@date_start,@date_end)
),

holidays as ( --table with holidays (USA)
SELECT * FROM (VALUES
('2016-01-01'),
('2016-01-18'),
('2016-02-15'),
('2016-05-30'),
('2016-07-04'),
('2016-09-05'),
('2016-10-10'),
('2016-11-11'),
('2016-11-24'),
('2016-12-26')) as t(d)
)

SELECT  c.d,
        CASE WHEN DATEPART(WEEKDAY,c.d) IN (1,7) THEN 0 --Saturday and Sunday, use (6,7) for Friday,Saturday
            WHEN h.d IS NOT NULL THEN 0
            ELSE 1 END as isWorking
FROM cte c
LEFT JOIN holidays h 
    ON c.d=h.d
OPTION (MAXRECURSION 1000); 

它将生成一个表格,其中包含2016年的所有日期和标记 - 是否正常工作。

答案 1 :(得分:0)

以下是如何做到这一点的高级概述..

创建一个以这种格式保存日期的虚拟表...

date     isholiday
20160101   1
20160102   0

现在,从您的主表中查看员工出勤情况,加入上表...

select empid,sum(Case when mt.datee is not null then 1  else 0 end) as workingdays
from
dummydatees dt
left join 
maintable mt
on dt.datee=mt.datee
where dt.isholiday=0

答案 2 :(得分:0)

此脚本将计算不包括星期六,星期日和节假日的总工作日。我必须列出所有假期,因为我没有假期表。您可以对其进行修改,使其符合您的要求。

DECLARE @MyCounter int = 0, @TempDate datetime,  @EndDate datetime;
SET @TempDate = DATEADD(d,1,'2017-5-27')
SET @EndDate = '2017-6-3'

WHILE @TempDate <= @EndDate
    BEGIN
    IF DATENAME(DW,@TempDate) = 'Sunday' OR DATENAME(DW,@TempDate) = 'Saturday'
        SET @MyCounter = @MyCounter
    ELSE IF @TempDate not in ('2017-1-1', '2017-1-16', '2017-2-20', '2017-5-29', '2017-7-4', '2017-9-4', '2017-10-9', '2017-11-11', '2017-12-25')
        SET @MyCounter = @MyCounter + 1

    SET @TempDate = DATEADD(d,1,@TempDate)
    CONTINUE

END
PRINT @MyCounter
PRINT @TempDate