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

时间:2016-02-22 21:16:16

标签: sql teradata

我有一张如下表格。我有前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:我想输出最大活动日期的频道名称。所以在上面的例子中,我希望新列在所有行中都说“会议”。

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

我尝试了以下但是我收到一个错误,说我需要在某处成功或先前声明。

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

我希望这种逻辑有效:

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

如果此版本有效。