Teradata中值为1的下一个日期行

时间:2018-01-05 00:12:18

标签: teradata

我需要在Teradata上输出以下内容:

DATE_HOME   WORKING_DAY
01/01/2018  0
02/01/2018  1
03/01/2018  1
04/01/2018  1
05/01/2018  1
06/01/2018  0
07/01/2018  0
08/01/2018  1
09/01/2018  1

Output required
DATE_HOME   WORKING_DAY Updated_DATE
01/01/2018  0           02/01/2018
02/01/2018  1           02/01/2018
03/01/2018  1           03/01/2018
04/01/2018  1           04/01/2018
05/01/2018  1           05/01/2018
06/01/2018  0           08/01/2018
07/01/2018  0           08/01/2018
08/01/2018  1           08/01/2018
09/01/2018  1           09/01/2018

2 个答案:

答案 0 :(得分:2)

对于first_value来说,这是一项简单的任务:

first_value(case when WORKING_DAY = 1 then DATE_HOME end ignore nulls)
over (order by DATE_HOME
      rows between current date and unbounded following)

将非业务日期更改为NULL,然后搜索第一个非NULL值。

编辑:

事实上,当您按同一列排序时,不需要first_value,简单的min也适用:

min(case when WORKING_DAY = 1 then DATE_HOME end)
over (order by DATE_HOME
      rows between current date and unbounded following)

答案 1 :(得分:0)

好主,这很难看,但似乎有效。我无法访问TD系统,所以它比它更加冗长:

SELECT 
    date_home,
    working_day,
    CAST(
        CASE 
            -- If current date is a non-work day, add appropriate number of days to non-work day to get next work-day
            WHEN working_day = 0 THEN date_home + INTERVAL '1' DAY * (ROW_NUMBER() OVER(PARTITION BY update_date ORDER BY date_home DESC))
            ELSE date_home 
        END 
    AS DATE) AS Update_date
FROM (
    SELECT 
        date_home,
        working_day,
        CASE 
            -- If current and previous days were non-work days, group row by PrevWorkDay value
            WHEN MIN(working_day) OVER(ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) = 0 AND working_day = 0 THEN MIN(PrevWorkDay) OVER(ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) 
            ELSE PrevWorkDay 
        END AS Update_Date
    FROM (
        SELECT 
            date_home, 
            working_day, 
            CASE 
                -- Track "baseline" previous date_home value for new group of "non-work day" rows
                WHEN COALESCE(MIN(working_day) OVER(ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING), 1) = 1 AND working_day = 0 THEN COALESCE(MIN(Date_Home) OVER(ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING), date_home) 
                ELSE NULL 
            END AS PrevWorkDay
        FROM holiday_calendar
    ) src
) src
ORDER BY date_home

这假设您的源数据存储在名为“holiday_calendar”的表中。

COALESCE用于处理结果集中的第一行,它不能计算前一行的值,因为没有前一行。

尝试一下,让我知道。