简体   繁体   中英

Complex Self-Join

I have a problem with a view, I'm working with Sql Server. I have a table like this:

+-------+------+
| Start | End  |
+-------+------+
|     1 | Null |
|     3 | 4    |
|     6 | 9    |
+-------+------+

This table represents a series of timeframe, if End is Null this means that it has not finished, but there may be short breaks (3-4 and 6-9), I would like to create a view that will show all the timeframes like this:

+-------+------+
| Start | End  |
+-------+------+
|     1 | 3    |
|     3 | 4    |
|     4 | 6    |
|     6 | 9    |
|     9 | Null |
+-------+------+

I can't find a solution. I tried more than than an hour with no results.

I think you want union all with lead() :

select start, lead(start) over (order by start)
from ((select t.start as start from likethis t
      ) union all
      (select t.end from likethis t
      )
     ) t
where start is not null
order by start;

In earlier versions of SQL Server, you can use cross apply :

with t as (
      select t.start as start from likethis t
      union all
      select t.end from likethis t
     )
select t.start, tnext.start 
from t cross apply
     (select top 1 t2.*
      from t t2
      where t2.start > t.start
      order by t2.start desc
     ) tnext
order by start;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM