[英]Complex Self-Join
我的視圖有問題,我正在使用Sql Server。 我有一張這樣的桌子:
+-------+------+
| Start | End |
+-------+------+
| 1 | Null |
| 3 | 4 |
| 6 | 9 |
+-------+------+
該表代表一系列時間范圍,如果End為Null,則表示它尚未完成,但是可能會有短暫的中斷(3-4和6-9),我想創建一個視圖來顯示所有時間范圍,例如這個:
+-------+------+
| Start | End |
+-------+------+
| 1 | 3 |
| 3 | 4 |
| 4 | 6 |
| 6 | 9 |
| 9 | Null |
+-------+------+
我找不到解決方案。 我嘗試了一個多小時,但沒有結果。
我認為您想將union all
與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;
在早期版本的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.