3

Alright, let's say I have a table that looks like this:

 ID   | DATE
 2  | 2010-08-12
 2  | 2010-08-16 
 2  | 2010-08-17 
 2  | 2010-12-21 
 2  | 2010-12-22 
 2  | 2011-05-25 

anyone have an idea on how to query it so the data looks like

 ID   | STARTDATE  | ENDDATE
 2  | 2010-08-12 | 2010-08-15
 2  | 2010-08-16 | 2010-08-16
 2  | 2010-08-17 | 2010-12-20
 2  | 2010-12-21 | 2010-12-21
 2  | 2010-12-22 | 2010-05-25
James
  • 572
  • 3
  • 9
  • 17

3 Answers3

6

I will not put here the ID as I see it is irrelevant in the query. If you wish you will put it later. This is a MSSQL query.

select tb1.date as startdate,dateadd(d,-1,tb2.date) as enddate
from the_table tb1
join the_table tb2 on tb2.date>tb1.date
left join the_table tb3 on tb1.date<tb3.date and tb3.date<tb2.date
where tb3.date is null

It can be easily translated for other DB types.

Dumitrescu Bogdan
  • 7,127
  • 2
  • 23
  • 31
  • This is actually a really useful approach for a couple of scenarios. Very cool. – Mike Goatly Mar 25 '11 at 11:09
  • very old post.. but thought I would add a couple things: the OP has a date in 2011 in the first table, which i think should be the end date of the last record in the second table. Also, this would also imply that you would wawnt an additional record that starts on the 2011 date, and hasn't ended yet. for that, use this answer but union it with the currently active records eg. union select tbl1.date, null from (select date, max(date) over (partition by id) current from the_table) tbl1 where date = current (note i've assumed we want to do this per ID) – da Bich Nov 13 '22 at 16:11
1

These two links will give you a rough idea.

Community
  • 1
  • 1
Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
1

if you have serialize id like ( 1,2,3,4,5,..) then you can get the above with this query with 1 extra data at last but you can omit that the folloowing is the mysql query

SELECT startdate, ( select startdate - INTERVAL 1 DAY from tester a where a.id = b.id +1) as enddate FROM tester b

Ujjwal Manandhar
  • 2,194
  • 16
  • 20