【问题标题】:Get the rolling Last_Date for a transactions SQL Teradata获取事务 SQL Teradata 的滚动 Last_Date
【发布时间】:2021-07-31 03:28:51
【问题描述】:

请给我一个简单的表格,上面有两列,如下所示

|Connect_Date|TRX_Count|
|------------+---------|
|1-May       |         |
|2-May       |         |
|3-May       |        3|
|4-May       |         |
|5-May       |         |
|6-May       |        4|
|7-May       |         |
|8-May       |        7|
|9-May       |         |
|10-May      |       10|

我需要插入一个新列,其中最后一个日期为 TRX_Count 大于 0 或为空,结果将如下所示

|Connect_Date|TRX_Count|Last_Date|
|------------+---------+---------|
|1-May       |         |3-May    |
|2-May       |         |3-May    |
|3-May       |        3|3-May    |
|4-May       |         |6-May    |
|5-May       |         |6-May    |
|6-May       |        4|6-May    |
|7-May       |         |8-May    |
|8-May       |        7|8-May    |
|9-May       |         |10-May   |
|10-May      |       10|10-May   |

【问题讨论】:

    标签: sql teradata window-functions


    【解决方案1】:

    使用累积最小值:

    select t.*,
           min(case when trx_count is not null then connect_date end) over (order by connect_date rows between current row and unbounded following) as last_date
    from t;
    

    lead(ignore nulls):

    select t.*
           lead(case when trx_count is not null then connect_date end ignore nulls) over (order by connect_date)
    from t;
    

    【讨论】:

    • 它工作得很好,但是如果最后一个有 trx_count 的日期是 8-May 而不是 10_may 那么接下来的几天返回 null
    • @AhmedAbdelkader 。 . .这假定connect_date 存储为正确的date,而不是字符串。如果是字符串修复数据.
    • 是的,这是一个正确的日期,而不是一个字符串,所以如果我试图通过条件 where connect_date = (select Max(connect_date) from t) 获取每个客户的最后一次观察结果,它会返回一个空值
    • @AhmedAbdelkader 。 . .这个答案不起作用吗?这就是你不接受它的原因吗?
    • @AhmedAbdelkader 。 . .我有点困惑。该条件不是您在此处提出的问题的一部分。这回答了您实际提出的问题。
    【解决方案2】:

    这会在开头和结尾填充 NULL:

    coalesce(min(case when TRX_Count is not null then Connect_Date end)
             over (order by Connect_Date desc
                   rows unbounded preceding)
            ,max(case when TRX_Count is not null then Connect_Date end) over ()
            )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多