我基于this solution在sql上创建了类似于NETWORKDAYS的函数,它可以正确返回工作日,而记录(BEG和END)在工作日。
BEG END businessd
--------------------------------
01/01/2018 15/01/2018 10
--(15 days total)-(1st jan)-(4 weekends) = 10 | correct result
但是在某些情况下,周末会“存储” BEG或END,这会增加几天的时间:
BEG END businessd
--------------------------------
01/01/2018 28/01/2018 20
--(28 days total)-(1st jan)-(4 weekends) = 19 | incorrect result
我的代码在datediff
和BEG
之间进行了FIN
运算,并减去了存储在holydays
表中的周末和节假日
SELECT e.*,
DATEDIFF(DAY, cast(BEG as datetime), cast(FIN as datetime))+1 --sum end date day
-(SELECT
(DATEDIFF(WK, cast(BEG as datetime), cast(FIN as datetime)) )
+(CASE WHEN DATENAME(dw, cast(BEG as datetime)) = 'Sunday' THEN 1 ELSE 0 END)
+(CASE WHEN DATENAME(dw, cast(FIN as datetime)) = 'Saturday' THEN 1 ELSE 0 END)
) * 2
-(SELECT COUNT(*) FROM holydays nl
WHERE nl.FECHA BETWEEN cast(BEG as datetime) AND cast(FIN as datetime)
) AS businessd,
convert(nvarchar(6),cast(BEG as datetime),112) as iddate --new id based on fin
FROM e
ORDER BY original_ini,BEG
如何处理这些案件以正确计算工作日?
答案 0 :(得分:1)
您可以为此使用日历表。这样操作将非常容易。
您甚至可以处理银行假期
Check This和this (Calendar Table)
select * from calendar where isWorkDay = 1
将为您提供工作日,然后可以进行简单的加入,例如
select * from t
where exists
( select 1 from calendar where isWorkDay = 1 and calendar.dt betweenn t.beg and t.end)