![](/img/trans.png)
[英]SQL - need a query for the last_date for each user, max_date, min_date
[英]Get the rolling Last_Date for a transactions SQL Teradata
请我有一个包含两列的简单表格,如下所示
|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 或 null,结果将如下所示
|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 |
使用累积最小值:
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;
这会在开头和结尾填充 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 ()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.