简体   繁体   English

SQL连续日期范围

[英]SQL continuous date range

I'm stuck in something that looks simple in DB2, this is my table 我陷入了DB2中看起来很简单的问题,这是我的表

ID  | BEG_DT                    | END_DT            
----  ------------------------- ------------------------- 

1   |  2016-09-01 00:00:00.0    | 2016-09-30 00:00:00.0     
2   |  2016-10-01 00:00:00.0    | 2016-10-31 00:00:00.0         
3   |  2016-12-01 00:00:00.0    | 2016-12-31 00:00:00.0     
4   |  2017-01-01 00:00:00.0    | 2017-01-31 00:00:00.0     
5   |  2017-02-01 00:00:00.0    | 2017-02-28 00:00:00.0     
6   |  2017-04-01 00:00:00.0    | 2017-04-30 00:00:00.0     
7   |  2017-05-01 00:00:00.0    | 2017-05-31 00:00:00.0     
8   |  2017-06-01 00:00:00.0    | 2017-06-30 00:00:00.0     
9   |  2017-07-01 00:00:00.0    | null

I want a query that returns the continuous periods of begin date and end date, for example, in this case the query needs to return: 我想要一个查询,该查询返回开始日期和结束日期的连续时间段,例如,在这种情况下,该查询需要返回:

BEG_DT                    |END_DT            
------------------------- |------------------------- 
2016-09-01 00:00:00.0     |2016-10-31 00:00:00.0     
2016-12-01 00:00:00.0     |2017-02-28 00:00:00.0      
2017-04-01 00:00:00.0     |null 

Hi you can use recursion to find all continuous periods and then use days function to eliminate periods that are part of larger one . 嗨,您可以使用递归来查找所有连续的期间,然后使用“天”功能消除较大的期间中的某个期间。 for example 2017-05-01 to 2017-06-30 is part of 2017-04-01 to null. 例如,2017年1月5日至2017年6月30日为2017年4月1日的一部分,则为null。

WITH temp1 (
id
,beg_dt
,end_dt
)
AS (
SELECT m.*
FROM WORK.MYTABLE m
)
,temp2 (
id
,beg_dt
,end_dt
)
  AS (
    SELECT 1
    ,beg_dt
    ,end_dt
FROM temp1

UNION ALL

SELECT 2
    ,tt1.beg_dt
    ,tt2.end_dt
FROM temp1 tt1
    ,temp2 tt2
WHERE tt1.end_dt = tt2.beg_Dt - 1 day
)
  SELECT id
    ,beg_dt
    ,end_dt
  FROM temp2 a
  WHERE NOT EXISTS (
    SELECT 1
    FROM temp2 b
    WHERE a.beg_dt BETWEEN b.beg_Dt
            AND coalesce(b.end_dt, '9999-12-31')
        AND days(coalesce(b.end_dt, '9999-12-31')) - days(b.beg_dt) > days(coalesce(a.end_dt, '9999-12-31')) - days(a.beg_dt)
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM