Return每个日历月的工作日数

Return the working day number in each calendar month

我正在尝试计算每个日历月的工作日数。例如,在 11 月份,有 22 个工作日(1、2、3、...、22)。星期六和星期日将被视为前面的星期五(例如 11 月 1、2、3、4、5、5、5、6、7、8、9、10、10、10、11、...、22)。

我在下面写的逻辑不起作用。请问有人能帮我解决这个问题吗?

SELECT Date 
     , datepart(DW, DATE) AS DayName
     , DATENAME(DW, DATE) ax
     , datepart(DW, DATE)-1 AS DayName1
     , CASE WHEN datepart(DW,DATE)-1 IN (0,6) THEN 5 ELSE datepart(DW,DATE)-1 END bx
FROM [STAGING_4_6_DIM_CALENDAR_V2] 
ORDER BY 1 ASC

我想你可以使用 运行 和:

WITH cte AS (
    SELECT Date
         , CASE WHEN DATENAME(WEEKDAY, Date) IN ('SATURDAY', 'SUNDAY') THEN 0 ELSE 1 END AS wd
    FROM t
)
SELECT Date, SUM(wd) OVER (PARTITION BY YEAR(Date), MONTH(Date) ORDER BY Date)
FROM cte

2021 年 11 月 return:

1,2,3,4,5,5,5,6,7,8,9,10,10,10,11,12,13,14,15,15,15,16,17,18,19,20,20,20,21,22
 SELECT S.[DATE]
    ,X.WeekDayNumber
    ,DATENAME(dw, [DATE]) AS ax
    ,5 * X.WeekOfMonth +
        CASE
            WHEN X.WeekDayNumber > 5
            THEN 5
            ELSE X.WeekDayNumber
        END
        - X.FirstDayOfMonthOffset AS bx
FROM [STAGING_4_6_DIM_CALENDAR_V2] S
    CROSS APPLY
    (
        VALUES
        (
            -- iso day of week regardless of locale
            (DATEPART(dw, [DATE])  + @@DATEFIRST + 5) % 7 + 1
            -- Zero based week of month
            ,DATEPART(iso_week, [DATE]) % 53
                - DATEPART(iso_week, DATEADD(day, 1, EOMONTH([DATE], -1))) % 53
            -- Zero based first day of month offset. Monday = 0 to Sunday =6
            ,(DATEPART(dw, DATEADD(day, 1, EOMONTH([DATE], -1)))  + @@DATEFIRST + 5) % 7
        )
    ) X (WeekDayNumber, WeekOfMonth, FirstDayOfMonthOffset)
ORDER BY [DATE];