使用CalendarTable SQL Server 2008计算NETWORKDAYS

时间:2019-02-11 20:11:03

标签: sql sql-server sql-server-2008 datediff

以前,我创建了一个SELECT来计算营业日(周末/节假日),但对于每个记录在特定日期范围内均无效。建议我使用日历表,该日历表实际上可以满足我所保留的其他要求,但是我不知道如何在工作日计算INIEND

我试图用半左联接和联接(也建议)进行SELECT,但似乎根本无法计算。

这是日历表:

CalendarId  DateValue               DayNumberOfWeek NameOfDay  NameOfMonth WeekOfYear  JulianDay   USAIsBankHoliday USADayName
----------- ----------------------- --------------- ---------- ----------- ----------- ----------- ---------------- -------------------
20100101    2010-01-01 00:00:00.000 5               Viernes    Enero       1           1           1                Año nuevo

我的桌子:

INI                            FIN                            DD --DATEDIFF BETWEEN DATES
------------------------------ ------------------------------ -----------
20180129                       20180211                       14

我尝试计算营业日

SELECT CONVERT(NVARCHAR,INI,112) AS INI, 
    CONVERT(NVARCHAR,FIN,112) AS FIN, 
    DATEDIFF(DD, INI, FIN)+1 AS DD 
FROM HISTORICOLICMED T
WHERE EXISTS(
    SELECT 1 FROM CALENDAR C
    WHERE T.INI = C.CALENDARID and T.FIN = C.CALENDARID
    AND C.USAISBANKHOLIDAY = 0 BETWEEN T.INI AND T.FIN)

我希望得到正确的工作日计算,包括假期,因此对于上面的示例,我将得到类似的信息:

INI                            FIN                            DD     ND
------------------------------ ------------------------------ ----- -----
20180129                       20180211                       14     10

2 个答案:

答案 0 :(得分:1)

从子菜单中选择日历表中INIFIN之间的行数,即工作日。

SELECT CONVERT(NVARCHAR,INI,112) AS INI, 
    CONVERT(NVARCHAR,FIN,112) AS FIN, 
    DATEDIFF(DD, INI, FIN)+1 AS DD, 
    (SELECT COUNT(*) FROM CalendarTable WHERE ...) AS ND
FROM HISTORICOLICMED 

答案 1 :(得分:1)

建议的解决方案:

set datefirst 1;
select INI
    ,FIN
    , DATEDIFF(DD, INI, FIN)+1 as DD
    ,(DATEDIFF(DD, INI, FIN)+1)
    -(DATEDIFF(WK, INI, FIN)*2)
    -(case DATEPART(DW, INI)    when 7 then 1 else 0 end)
    -(case DATEPART(DW, FIN)    when 6 then 1 else 0 end)
    -(select COUNT(*) from CALENDAR
        where DateValue between INI and FIN
        and USAIsBankHoliday = 1)
    as ND -- Working days except US Bank holidays
from HISTORICOLICMED;