Skip to content
Advertisement

SQL to find start and end date for an ID

I have a table with ID, start_date and end_date columns.

Table:

I want to write a query to get the following output:

Output:

Advertisement

Answer

You can do a cumulative sum to solve this variation of the gaps-and-island problem:

Demo on DB Fiddle:

ID | START_DATE | END_DATE  
-: | :--------- | :---------
 1 | 01/01/2017 | 01/01/2020
 2 | 01/01/2016 | 01/01/2018
 2 | 01/01/2019 | 01/01/2020
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement