【发布时间】:2014-09-29 19:44:32
【问题描述】:
我有一个包含以下列和数据的表格。数据描述了某些客户活动时期
cust_id s_date e_date
11111 01.03.2014 31.03.2014
11111 10.04.2014 30.04.2014
11111 01.05.2014 10.05.2014
11111 15.06.2014 31.07.2014
22222 01.04.2014 31.05.2014
22222 01.06.2014 30.06.2014
22222 01.07.2014 15.07.2014
我想写一个查询来给出这个结果:
cust_id s_date e_date
11111 01.03.2014 10.05.2014
11111 15.06.2014 31.07.2014
22222 01.04.2014 15.07.2014
查询结果的目的是当客户 IN-activity 周期小于 15 天时,将行“合并”为一行。我可以处理“前面的 1 行”,但如果需要合并 3 行或更多行,则它不起作用。我想不出如何编写这个查询。
我查询前的“一半”1 行:
SELECT cust_id
, start_date as current_period_start_date
, end_date as current_period_end_date
, end_date+15 as current_period_expired_date
, coalesce(
min(current_period_expire_date)
over(partition by cust_id
order by start_date
rows between 1 preceding and 1 preceding)
, cast('1900-01-01' as date)) as previous_period_expire_date
, case
when current_period_start_date <= previous_period_expire_date
then min(current_period_start_date)
over(partition by cust_id
order by start_date
rows between 1 preceding and current row)
else current_period_start_date
end as new_current_period_start_date
FROM MY_DB.my_table
. . .
另外,是否可以像这样将前置变成动态方式?
... over(partition by ... order by ... rows between X preceding and current row)
【问题讨论】: