【问题标题】:How to get previous row values Teradata如何获取先前的行值 Teradata
【发布时间】:2021-09-18 13:29:24
【问题描述】:

我有以下格式的数据

 Id    Code    Date         Amount       Type
 101   B25     5/4/2020      $500         C
 101   A15     5/5/2020      $100         D
 101   D15     5/5/2020      $200         D
 102   B35     6/2/2020      $400         C
 102   A15     6/2/2020      $50          D

我需要以下内容

 Id    Code    Date         Amount       Type  C_Date          C_Amount
 101   A15     5/5/2020      $100         D    5/4/2020         $500
 102   A15     6/2/2020      $50          D    6/2/2020         $400

对于所有 Code='A15' 我需要上一行的日期和金额,其中 Type='C'

我做了这个

 Select id, Amount, Date,
  sum(Amount) over (partition by ID ROWS between UNBOUNDED PRECEDING and CURRENT ROW) as 
   C_Amount,
  Max(Date) over (partition by ID ROWS between UNBOUNDED PRECEDING and CURRENT ROW) as 
   C_Date
 from Table
 where code='A15' or Type='C'

输出不是我们想要的

 Id    Code    Date         Amount       Type  C_Date          C_Amount
 101   A15     5/5/2020      $100         D    ***5/5/2020         $100***
 102   A15     6/2/2020      $50          D    ***6/2/2020         $50***

感谢任何帮助

【问题讨论】:

    标签: row teradata lag


    【解决方案1】:

    答案集与您的查询不匹配,它也将包含“C”行。

    ROWS between UNBOUNDED PRECEDING and CURRENT ROW 是一个组和

    您需要ROWS between 1 PRECEDING and 1 PRECEDNG 和一个 ORDER BY 来获取上一行的值。

    最好切换到 LAG 或 LAST_VALUE,这更简单,并且允许处理“A15”和前一个“C”行之间的额外行:

     Select id, Amount, Date,
      LAG(case when Type='C' then Amount end IGNORE NULLS)
      over (partition by ID
            order by date) as C_Amount,
      LAG(case when Type='C' then date end IGNORE NULLS)
      over (partition by ID
            order by date) as C_Date
     from Table
     where code='A15' or Type='C'
     qualify code='A15';
    

    【讨论】:

      猜你喜欢
      • 2013-05-16
      • 1970-01-01
      • 2022-11-02
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 2021-10-18
      相关资源
      最近更新 更多