SQL查询创建开始日期和结束日期

Jam*_*mes 3 sql

好吧,假设我有一个看起来像这样的表:

 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 
Run Code Online (Sandbox Code Playgroud)

任何人都知道如何查询它所以数据看起来像

 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
Run Code Online (Sandbox Code Playgroud)

Dum*_*dan 5

我不会在这里放置ID,因为我认为它在查询中是无关紧要的.如果你愿意,你会稍后再说.这是一个MSSQL查询.

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
Run Code Online (Sandbox Code Playgroud)

它可以轻松转换为其他数据库类型.