0

Given a table with columns representing a start and end:

Start        End
01/01/2016   03/01/2016
01/01/2016   06/01/2016

I'm trying to build a query that can recognize that the distinct set of ranges is the following:

[01/01/2016, 03/01/2016)
[03/01/2016, 06/01/2016)

What is this concept called and how can I achieve it with SQL ?

1
  • Well, how exactly would you define the set of ranges? If you try to answer this question you might find yourself very close to the answer... Commented Apr 14, 2017 at 21:13

2 Answers 2

3

You can bring all the dates together and use lead():

with d as (
      select start as dte
      from t
      union  -- on purpose to remove duplicates
      select end as dte
      from t
     )
select dte as start, lead(dte) over (order by dte) as end
from d;

If you want to prevent the final NULL value . . .

select d.*
from (select dte as start, lead(dte) over (order by dte) as end
      from d
     ) d
where end is not null;
Sign up to request clarification or add additional context in comments.

Comments

0

select lag(end_date,1,start_date) over(order by end_date) start_date,end_date from jtest14;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.