【问题标题】:SQL - Output column based on latest dateSQL - 基于最新日期的输出列
【发布时间】:2016-02-22 21:16:15
【问题描述】:

我有一张如下表。我有前 4 列。最后两个是我要添加的。我在 Teradata 上。

custid  channel activity_date   close_date  lastchannel days_before_close
11      email   2-Jan-16        3-Feb-16    meeting     28
11      call    3-Jan-16        3-Feb-16    meeting     28
11      mail    4-Jan-16        3-Feb-16    meeting     28
11      email   5-Jan-16        3-Feb-16    meeting     28
11      meeting 6-Jan-16        3-Feb-16    meeting     28

1) lastchannel:我想输出最大活动日期的频道名称。因此,在上面的示例中,我希望新列在所有行中都显示“会议”。

2) 截止日期和最后一个活动日期之间的天数:在这种情况下,2 月 3 日和 1 月 6 日之间的天数为 28。

我尝试了以下方法,但我收到一条错误消息,提示我在某处需要成功或先于语句。

first_value(channel) over (partition by cust_id, activity_date order by activity_date desc) as lastchannel

【问题讨论】:

    标签: sql teradata


    【解决方案1】:

    这与 Gordon 的相同,根据您的评论,您可能想要这样:

    first_value(case when activity_date <= close_date then channel end ignore nulls) 
    over (partition by cust_id
          order by activity_date desc) as lastchannel
    

    第二个是

    close_date - max(activity_date) over (partition by cust_id) as days_before_close
    

    根据您的评论:

    close_date - max(case when activity_date <= close_date then activity_date end)
                 over (partition by cust_id) as days_before_close
    

    【讨论】:

    • 嗨,我如何在 #2 上设置相同的 where 条件?即我需要 days_before_close 结束前的最后一个活动
    【解决方案2】:

    我希望这个逻辑可以工作:

    first_value(channel) over (partition by cust_id
                               order by activity_date desc
                              ) as lastchannel
    

    也许你需要一个显式的窗口子句:

    first_value(channel) over (partition by cust_id
                               order by activity_date desc
                               rows between unbounded preceding and current row
                              ) as lastchannel
    

    甚至:

    first_value(channel) over (partition by cust_id
                               order by activity_date desc
                               rows between current row and current row
                              ) as lastchannel
    

    如果这个版本有效。

    【讨论】:

    • 谢谢,第一个有效。我需要设置这样的 where 条件,但这给了我一个错误first_value(channel) over (partition by cust_id where activity_date &lt;= close_date order by activity_date desc) as lastchannel
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多