缩放 CASE WHEN 以检索非假期日期

Scale CASE WHEN to retrieve non-holiday dates

我有 table 包含开始日期和结束日期的记录,所以我必须获取从星期五开始的每条记录,如果星期五是假期,则获取星期四,如果星期五和星期四是假期,得到星期三等等...

目前我有两个 table TableA 用于记录,Calendar 用于休假。

我的 TableA 看起来像这样:

id beg         end
--------------------------
1  11/01/2019  14/01/2019
2  10/01/2019  14/01/2019
3  09/01/2019  15/01/2019
...

日历看起来像这样:

iddate    date        weekday isholiday
---------------------------------------
20190109  09/01/2019  3       0 --0=False / 1=True
20190110  10/01/2019  4       0
20190111  11/01/2019  5       1
...

对于两个 tables,我使用 WHERE EXISTS 来获取实际显示结果的星期五和假日条件:

SELECT *
FROM TableA t
WHERE EXISTS (SELECT 1
              FROM dbo.Calendar AS c
              WHERE c.date = CAST(t.BEG AS DATETIME)
                AND c.weekday = CASE
                                    WHEN (C.weekday = 5 AND C.isholiday = 0)  
                                       THEN 5 --keep friday
                                    --WHEN ((C.weekday= 4 AND C.isholiday= 1) OR (C.weekday= 5 AND C.isholiday= 1)) THEN 3 --keep wednesday / not working
                                       ELSE 4 --keep thursday
                                    END
                AND DATEPART(yyyy, T.beg) = 2019)
ORDER BY 
    CAST(INI AS [datetime])

如果周五是节假日,会显示:

id beg         end
--------------------------
2  10/01/2019  14/01/2019
3  09/01/2019  15/01/2019

如果周五和周四是节假日,应该显示:

id beg         end
--------------------------
3  09/01/2019  15/01/2019

用这个 WHEN ((C.weekday= 4 AND C.isholiday= 1) OR (C.weekday= 5 AND C.isholiday= 1)) 扩大它只会破坏整个查询,我得到 - 几乎 - 随机日期。有什么方法可以在不过度扩展查询的情况下扩大它?

根据您的评论,我会使用一个常见的 table 表达式:

;With cte_Last_Day_Of_Week
As
(
    Select 
        c.iddate
        , c.date
        , Row_Number() Over (Partition By DatePart(Week, c.date) Order By c.date Desc) As RN
    From dbo.Calendar As c
    Where c.isholiday = 0
)

Row_Number() 将标记每周最后一个非节假日的日期,值为 1。然后你可以像 table.

一样加入反对。

让我知道这是否有意义。