基于前一天的索引周末

问题描述 投票:0回答:1

我有一个查询,其选择语句如下:

SELECT 
    CAST(p.date AS DATE) AS 'Date', 
    x.Month,
    x.Version,
    x.Value AS 'fcst',
     CASE WHEN isholiday = 0 
     THEN ROW_NUMBER() OVER (PARTITION BY x.Department, x.Month, p.isholiday ORDER BY p.date)
     ELSE 0
     END AS 'Index'

输出看起来像这样:

 Date       Month   Version fcst    isholiday   Index
2020-01-01  January 3plus9  3679    1            0
2020-01-02  January 3plus9  3679    0            1
2020-01-03  January 3plus9  3679    0            2
2020-01-04  January 3plus9  3679    1            0
2020-01-05  January 3plus9  3679    1            0
2020-01-06  January 3plus9  3679    0            3
2020-01-07  January 3plus9  3679    0            4
2020-01-08  January 3plus9  3679    0            5
2020-01-09  January 3plus9  3679    0            6
2020-01-10  January 3plus9  3679    0            7
2020-01-11  January 3plus9  3679    1            0
2020-01-12  January 3plus9  3679    1            0
2020-01-13  January 3plus9  3679    0            8
2020-01-14  January 3plus9  3679    0            9
2020-01-15  January 3plus9  3679    0            10
2020-01-16  January 3plus9  3679    0            11
2020-01-17  January 3plus9  3679    0            12
2020-01-18  January 3plus9  3679    1            0
2020-01-19  January 3plus9  3679    1            0
2020-01-20  January 3plus9  3679    0            13

索引列基于'isHoliday'列。如case语句所示,在isHoliday = 1的每个点,索引显示为0。相反,如果天<> 1,则我需要Index值来显示为它上面的Index的值。

例如,在日期= 1月4日和1月5日的行上,索引需要显示为2。我试图更改case语句,但是无法找到解决方案。

sql sql-server partition
1个回答
0
投票

我认为您想要holiday = 0的累计计数:

select sum(case when isholiday = 0 then 1 else 0 end) over (partition by department, month order by date) as my_index

如果holiday仅采用两个值,则可以简化为:

select sum(1 - isholiday) over (partition by department, month order by date) as my_index
© www.soinside.com 2019 - 2024. All rights reserved.