SQL - 基于最新日期的输出列

SQL - Output column based on latest date

我有一个 table 如下所示。我有前 4 列。最后2个是我要添加的。我在 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:我想输出最大 activity 日期的频道名称。所以在上面的示例中,我希望新列在所有行中显示 "meeting"。

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

我尝试了以下操作,但收到一条错误消息,提示我需要某处的 successes 或 preceding 语句。

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

我希望这个逻辑有效:

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

如果这个版本有效。

这与 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