如何删除列中两个数值之间的所有行

时间:2018-05-31 07:28:12

标签: sql sql-server tsql gaps-and-islands

我的表格有两列,idtyp

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

4 个答案:

答案 0 :(得分:3)

试试这个

DECLARE @idtype1 int, @idtype2 int

DECLARE type_cursor CURSOR FOR   
SELECT a.ID as ID_TYPE_1, b.ID as ID_TYPE_2  
FROM (SELECT ID, ROW_NUMBER() OVER(ORDER BY_ID) AS RN
    FROM TABLE WHERE TYPE = 1) a
INNER JOIN (SELECT ID, ROW_NUMBER() OVER(ORDER BY_ID) AS RN
        FROM TABLE WHERE TYPE = 2) b
    ON a.RN = b.RN

OPEN type_cursor  

FETCH NEXT FROM type_cursor   
INTO @idtype1, @idtype2  

WHILE @@FETCH_STATUS = 0  
BEGIN  
    DELETE FROM TABLE WHERE ID BETWEEN @idtype1 AND @idtype2

END

答案 1 :(得分:3)

这是一个经典的差距和岛屿问题类型的问题。 我建议您在空白和岛屿上阅读这篇优秀的 article

您可以使用下面的查询 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

答案 2 :(得分:3)

首先,您必须确定要删除的内容的边界:

and sic_name_txt='CORPORATE BONDS' 
and chd_column_header_txt='Percentage'
and chd_column_header_text_txt='pgperc1'

结果:

SELECT
    T1.id as StartId,
    (SELECT MIN(T2.id) from @tb1 T2 WHERE T1.id < T2.id and T2.typ = 2) as EndId
from @tb1 T1
WHERE T1.typ = 1

然后,您可以在CTE(公用表表达式)中使用此查询来执行实际删除:

StartId  EndId
1        3
5        6
9        13
15       NULL

答案 3 :(得分:0)

此查询应该有效

delete from @tb1 where id < 13 and id > 9

删除typ在10到12之间[包括边框]