gpt4 book ai didi

sql - T-SQL 中的日期循环

转载 作者:行者123 更新时间:2023-12-02 09:03:32 26 4
gpt4 key购买 nike

我需要编写一个查询来显示不间断的时间间隔。示例:

输入:

create table calc(Id int, StartDate DATE, EndDate DATE);
insert into calc values(1, '2019-01-01', '2019-01-02');
insert into calc values(2, '2019-01-02', '2019-01-03');
insert into calc values(3, '2019-01-03', '2019-01-04');
insert into calc values(4, '2019-01-14', '2019-01-15');
insert into calc values(5, '2019-01-16', '2019-01-17');
insert into calc values(6, '2019-01-17', '2019-01-18');
insert into calc values(7, '2019-01-25', '2019-01-26');
insert into calc values(8, '2019-02-03', '2019-02-04');
insert into calc values(9, '2019-02-04', '2019-02-05');
insert into calc values(10, '2019-03-01', '2019-03-02');

输出:

    StartDate , EndDate 
'2019-01-01', '2019-01-04'
'2019-01-14', '2019-01-15'
'2019-01-16', '2019-01-18'
'2019-01-25', '2019-01-26'
'2019-02-03', '2019-02-05'
'2019-03-01', '2019-03-02'

我认为我们需要逐行使用函数DATEDIFF。问题是我不知道如何访问索引。或者这个问题可以更容易解决吗?

最佳答案

这是一种间隙与岛屿问题。使用 lag() 查看相邻行是否重叠。对间隙进行累加,然后聚合:

select min(startdate), max(enddate)
from (select c.*,
sum(case when prev_ed = startdate then 0 else 1 end) over
(order by startdate) as grp
from (select c.*,
lag(enddate) over (order by startdate) as prev_ed
from calc c
) c
) c
group by grp
order by min(startdate);

Here是一个数据库<> fiddle 。

关于sql - T-SQL 中的日期循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61149795/

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