仅保留Teradata中特定数据部分的值

时间:2018-06-26 21:17:03

标签: teradata teradata-sql-assistant

下面是我上一个主题的链接。 Retain values till there is a change in value in Teradata

它按照社区成员@Dnoeth的建议工作。只能对部分数据进行保留吗?

即,仅保留Dep为A或B的数据的数据。当Dep为C时,只需使用相同的值作为输入,而无需保留到特定值。

Data:
Cust_id Balance st_ts          Dep
123     1000    27MAY2018 A
123     350     31MAY2018  A
256     2000   29MAY2018  B
345     1000   28APR2018   C
345     1200   26MAY2018   C

输出要求:

Cust_id Balance st_ts         Dep
123     1000    27MAY2018 A
123     1000    28MAY2018 A
123     1000    29MAY2018 A
123     1000    30MAY2018 A
123     350     31MAY2018  A
256     2000   29MAY2018  B
256     2000   30MAY2018  B
256     2000    31MAY2018 B
345     1000   28APR2018   C
345     1200   26MAY2018   C

使用的查询:

Wth cte
{
  SELECT customer_id, bal, st_ts,
      -- return the next row's date
      Coalesce(Min(st_ts)
               Over (PARTITION BY customer_id 
                     ORDER BY st_ts
                     ROWS BETWEEN 1 Following AND 1 Following)
              ,Date '2018-06-01') AS next_Txn_dt
   FROM BAL_DET;
}
SELECT customer_id, bal
  ,Last(pd) -- last day of the period
FROM cTE
-- make a period of the current and next row's date
-- and return one row per day
EXPAND ON PERIOD(ST_TS, next_Txn_dt) AS pd;

谢谢 桑迪

1 个答案:

答案 0 :(得分:0)

您可以添加一个案例以检查Dep = 'C'

WITH cte AS 
(  SELECT customer_id, bal, st_ts, dep,
      -- return the next row's date
      CASE
        WHEN dep = 'C' 
           THEN st_ts +1 -- simply increase date
        ELSE
           Coalesce(Min(st_ts)
                    Over (PARTITION BY customer_id 
                          ORDER BY st_ts
                          ROWS BETWEEN 1 Following AND 1 Following)
                   ,DATE '2018-06-01')
      END AS next_Txn_dt
   FROM BAL_DET
)
SELECT customer_id, bal
  ,Last(pd) -- last day of the period
  ,dep
FROM cTE
-- make a period of the current and next row's date
-- and return one row per day
EXPAND ON PERIOD(ST_TS, next_Txn_dt) AS pd