gpt4 book ai didi

SQL - 如果日期连接则合并行

转载 作者:行者123 更新时间:2023-12-04 23:45:56 25 4
gpt4 key购买 nike

我有包含以下行的表:clientid、startdate 和 enddate。同一 clientid 的日期不能重叠。如果日期连接,我想为每个客户合并行。

表格看起来像这样:

clientid  startdate      enddate
1 10.10.2017 12.10.2017
1 12.10.2017 13.10.2017
1 13.10.2017 17.10.2017
1 10.11.2017 17.11.2017
1 17.11.2017 23.11.2017
1 12.12.2017 14.12.2017
2 10.11.2017 15.11.2017
2 01.12.2017 02.12.2017
2 02.12.2017 05.12.2017

决赛 table 应该是这样的:

clientid  startdate      enddate
1 10.10.2017 17.10.2017
1 10.11.2017 23.11.2017
1 12.12.2017 14.12.2017
2 10.11.2017 15.11.2017
2 01.12.2017 05.12.2017

谢谢你的帮助。

最佳答案

您可以将这样的逻辑与 sum 聚合和 lag 窗口函数一起使用,如下所示:

select clientid, min(startdate) as startdate, max(enddate) as enddate
from
(
select tt.*, sum(grp) over (order by clientid, startdate) sm
from
(
with t(clientid, startdate, enddate) as
(
select 1, date'2017-10-10', date'2017-10-12' from dual union all
select 1, date'2017-10-12', date'2017-10-13' from dual union all
select 1, date'2017-10-13', date'2017-10-17' from dual union all
select 1, date'2017-11-10', date'2017-11-17' from dual union all
select 1, date'2017-11-17', date'2017-11-23' from dual union all
select 1, date'2017-12-12', date'2017-12-14' from dual union all
select 2, date'2017-11-10', date'2017-11-15' from dual union all
select 2, date'2017-12-01', date'2017-12-02' from dual union all
select 2, date'2017-12-02', date'2017-12-05' from dual
)
select clientid,
decode(nvl(lag(enddate) over
(order by enddate),startdate),startdate,0,1)
as grp, --> means prev. value equals or not
row_number() over (order by clientid, enddate) as rn, startdate, enddate
from t
) tt
order by rn
)
group by clientid, sm
order by clientid, enddate;

CLIENTID STARTDATE ENDDATE
---------- ---------- ----------
1 10.10.2017 17.10.2017
1 10.11.2017 23.11.2017
1 12.12.2017 14.12.2017
2 10.11.2017 15.11.2017
2 01.12.2017 05.12.2017

Rextester Demo

Step by Step Query Execution for better understanding

关于SQL - 如果日期连接则合并行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54314087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com