查询是否将周末(星期六和星期日)滚动到下一个工作日(星期一),如果是同一月份,

时间:2020-08-12 22:19:31

标签: sql sql-server

因此,如果我们从一个周末开始一个月,则第一天将成为周末,并且应该延期至工作日,同样,假期也应退回到前一天。

Date        RecognizedBusinessDateKey   RecognizedBusinessDateNumber
7/28/2020   20200728                    19
7/29/2020   20200729                    20
7/30/2020   20200730                    21
7/31/2020   20200731                    22
8/1/2020    20200803                    1
8/2/2020    20200803                    1
8/3/2020    20200803                    1
8/4/2020    20200804                    2

Date        RecognizedBusinessDateKey   RecognizedBusinessDateNumber
5/28/2020   20200528                    19
5/29/2020   20200529                    20
5/30/2020   20200529                    20
5/31/2020   20200529                    20
6/1/2020    20200601                    1
6/2/2020    20200602                    2
6/3/2020    20200603                    3
6/4/2020    20200604                    4

Date        RecognizedBusinessDateKey   RecognizedBusinessDateNumber
6/4/2020    20200604                    4
6/5/2020    20200605                    5
6/6/2020    20200605                    5
6/7/2020    20200608                    6
6/8/2020    20200608                    6
6/9/2020    20200609                    7

表中的数据看起来像这样

enter image description here

我尝试了以下查询

SELECT 
     d.Date
    ,d.DateKey
    ,d.IsBusinessDay
    ,d.MonthKey
    ,ISNULL(MAX(d2.DateKey),d.DateKey) AS RecognizedBusinessDateKey
    ,DENSE_RANK() OVER(PARTITION BY d.MonthKey ORDER BY ISNULL(MAX(d2.DateKey),d.DateKey)) AS RecognizedBusinessDateNumber
FROM dbo.DimDate d
    LEFT JOIN dbo.DimDate d2 
        ON d2.MonthKey <= d.DateKey
WHERE d2.IsBusinessDay = 'Business Day'
  AND d2.DateKey > 0
  AND d2.Date BETWEEN '8/1/2020' AND '8/31/2020'
GROUP BY 
     d.Date
    ,d.DateKey
    ,d.IsBusinessDay
    ,d.MonthKey

0 个答案:

没有答案