2つの列を持つテーブルがid
あり、typ
:
DECLARE @tb1 AS TABLE (id INT, typ INT)
INSERT INTO @tb1
(
id,
typ
)
VALUES
(1,1),(2,3),(3,2),(4,3),(5,1),(6,2),(7,3),(8,3),(9,1)
,(10,3),(11,3),(12,3),(13,2),(14,3),(15,1)
で並べ替えられid
た行を見るtyp = 1
と、ある行とtyp = 2
それに続く次の行の間にあるすべての行を削除したいと思います。
私はこの結果が欲しいです:
id typ
----------- -----------
1 1
3 2
4 3
5 1
6 2
7 3
8 3
9 1
13 2
14 3
15 1
これは、古典的なギャップと島の問題タイプの質問です。ギャップと島に関するこの優れた記事を読むことをお勧めします。
以下のようなクエリを使用できます See working demo
;
with BoundarySuspects as
(
select
a.*,
seqNumber=row_number() over( order by id asc)
from @tb1 a
where a.typ=1 or a.typ=2
),
GapMap as
(
select
GapFrom= a.id,
GapTill= b.id
from BoundarySuspects a
join
BoundarySuspects b
on a.typ=1 and b.typ=2 and b.seqNumber=a.seqNumber+1
)
select
t.*
from @tb1 t
left join
GapMap g
on t.id >GapFrom and t.id <GapTill
where GapFrom is NULL
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加