SQL-基于最新日期的输出列
我有一张像下面这样的桌子。我有前4列。最后两个是我想添加的。我在Teradata上SQL-基于最新日期的输出列,sql,teradata,Sql,Teradata,我有一张像下面这样的桌子。我有前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
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:我想输出最大活动日期的频道名称。因此,在上面的示例中,我希望新列在所有行中都显示“meeting”
2) 截止日期和最后一个活动日期之间的天数:在本例中,2月3日和1月6日之间的天数为28天
我尝试了下面的方法,但我得到一个错误,说我需要一个successed或prefers语句
第一个值(通道)(按客户id划分,按活动日期顺序按活动日期描述)作为最后一个通道
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(case when activity_date <= close_date then activity_date end)
over (partition by cust_id) as days_before_close
close\u date-max(活动日期时的情况谢谢,第一个有效。我需要像这样设置一个where条件,但这会给我一个错误first\u value(通道)over(按cust\u id划分,活动日期在哪里)Hi,我如何在#2上设置相同的where条件?也就是说,在关闭前我需要关闭最后一个活动的前几天
close_date - max(case when activity_date <= close_date then activity_date end)
over (partition by cust_id) as days_before_close