我有包含开始和结束日期记录的表,因此我必须获取从星期五开始的所有记录,如果星期五是假期,则获取星期四;如果星期五和星期四是假期,则获取星期三,依此类推上...
目前我有两个表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
...
对于两个表,我都使用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))
进行扩展只会破坏整个查询,并且我得到-几乎是随机的日期。有没有扩大查询范围的任何方法?
答案 0 :(得分:1)
根据您的评论,我将使用一个常见的表表达式:
;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
的值标记每个星期中最后一个非节假日的日期。然后,您可以像桌子一样加入。
让我知道这是否合理。