Search code examples
sqlteradatateradata-sql-assistant

How to differentiate the continuous and non-continuous date ranges based on ID column


ID  STRT_DT, ENT_DT 
1 9/14/2020,10/5/2020
1 10/6/2020,10/8/2020
1 10/9/2020,12/31/2199
2 7/14/2020,11/5/2020
2 11/21/2020,11/22/2020
2 11/23/2020,12/31/2199

Upon observing the above data for ID 1 and 2, The date ranges belongs to 1 are continuous and the ID 2 are non-continuous . I need pull the ID's which are continuous in SQL. Expected o/p : If any of the date range is not continuous (grouping by ID), that should not come into select clause. So the expectation of the SQL output is to get ID=1

Query using:

SELECT tab.ID,TAB.STRT_DT,TAB.ENT_DT,
STRT_DT - MIN(ENT_DT) OVER (PARTITION BY ID ORDER BY ENT_DT ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS diff, 
ENT_DT - MAX(STRT_DT) OVER (PARTITION BY ID ORDER BY ENT_DT ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) AS diff2 
FROM  tabLE QUALIFY diff <> 1 OR diff2 <> -1

Solution

  • select ID
    from
     (
       select 
          ID, 
          -- flag non-continous ranges, i.e. previous end is not equal to the day before current start
          case when STRT_DT - 1
                <> LAG(ENT_DT) OVER (PARTITION BY ID ORDER BY STRT_DT)
               then 1
               else 0
          end as flag
       from table
     ) as dt
    group by ID
    having sum(flag) = 0 -- only continous ranges exist