简体   繁体   English

复杂的自我加入

[英]Complex Self-Join

I have a problem with a view, I'm working with Sql Server. 我的视图有问题,我正在使用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: 该表代表一系列时间范围,如果End为Null,则表示它尚未完成,但是可能会有短暂的中断(3-4和6-9),我想创建一个视图来显示所有时间范围,例如这个:

+-------+------+
| 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() : 我认为您想将union alllead()

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 : 在早期版本的SQL Server中,可以使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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