复杂的自连接
Complex Self-Join
我的视图有问题,我正在使用 Sql 服务器。
我有一个 table 这样的:
+-------+------+
| Start | End |
+-------+------+
| 1 | Null |
| 3 | 4 |
| 6 | 9 |
+-------+------+
这个table代表一系列的timeframe,如果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服务器的早期版本中,您可以使用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;
我的视图有问题,我正在使用 Sql 服务器。 我有一个 table 这样的:
+-------+------+
| Start | End |
+-------+------+
| 1 | Null |
| 3 | 4 |
| 6 | 9 |
+-------+------+
这个table代表一系列的timeframe,如果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服务器的早期版本中,您可以使用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;