SQL合并重叠的时间间隔

时间:2019-12-04 19:29:47

标签: sql sqlite

我有一个这样的sqlite数据集

Startdate  | Enddate    | ID 
2019-04-29 | 2019-05-04 | 12
2019-04-23 | 2019-04-25 | 533
2019-04-23 | 2019-04-24 | 44
2019-04-24 | 2019-04-25 | 79

我正在尝试获取一个输出,该输出按循环从startdate到startdate再加上day到最后Endate的范围进行排序。 计划是从min(开始日期)到min(开始日期)+1和min(开始日期)加+2等所有观测值。

Range                 | ID
2019-04-23 2019-04-24 | 44
2019-04-23 2019-04-25 | 44
2019-04-23 2019-04-25 | 533
2019-04-23 2019-04-25 | 79
2019-04-23 2019-05-04 | 44
2019-04-23 2019-05-04 | 533
2019-04-23 2019-05-04 | 79
2019-04-23 2019-05-04 | 12

我不确定是否必须实现这一目标

1 个答案:

答案 0 :(得分:0)

我相信以下内容将提供您想要的结果:-

WITH cte(sdate,edate) AS 
    (
        SELECT (SELECT min(startdate) FROM mytable),(SELECT min(startdate) FROM mytable)
        UNION ALL 
            SELECT sdate,date(edate,'+1 days') 
            FROM cte 
            WHERE edate <= (
                SELECT max(enddate) FROM mytable
            ) 
            LIMIT 1000 /* just in case limit to 1000 rows */
    )
SELECT sdate||' '||edate AS Range, id 
FROM cte 
    JOIN mytable ON startdate >= sdate 
        AND enddate <= edate 
        AND edate IN (SELECT enddate FROM mytable)

示例/测试/演示

DROP TABLE IF EXISTS mytable;
CREATE TABLE IF NOT EXISTS mytable (startdate TEXT, enddate TEXT, id INTEGER PRIMARY KEY);
INSERT INTO mytable VALUES
    ('2019-04-29','2019-05-04',12),
    ('2019-04-23','2019-04-25',533),
    ('2019-04-23','2019-04-24',44),
    ('2019-04-24','2019-04-25',79)
;
WITH cte(sdate,edate) AS 
    (
        SELECT (SELECT min(startdate) FROM mytable),(SELECT min(startdate) FROM mytable)
        UNION ALL 
            SELECT sdate,date(edate,'+1 days') 
            FROM cte 
            WHERE edate <= (
                SELECT max(enddate) FROM mytable
            ) 
            LIMIT 1000 /* just in case limit to 1000 rows */
    )
SELECT sdate||' '||edate AS Range, id 
FROM cte 
    JOIN mytable ON startdate >= sdate 
        AND enddate <= edate 
        AND edate IN (SELECT enddate FROM mytable)
;
DROP TABLE IF EXISTS mytable;

结果是:-

enter image description here

  • 唯一的区别是ID列的顺序(您的预期结果看不到任何顺序)
  • 根据评论,不要求LIMIT 1000