34,838
社区成员




--> 测试数据:#
if object_id('tempdb.dbo.#') is not null drop table #
create table #(id int, status int)
insert into #
select 1, 1 union all
select 2, 1 union all
select 3, 1 union all
select 4, 0 union all
select 5, 0 union all
select 6, 1 union all
select 7, 0 union all
select 8, 0 union all
select 9, 0 union all
select 10, 0 union all
select 11, 1 union all
select 12, 0 union all
select 13, 0 union all
select 14, 0 union all
select 15, 0 union all
select 16, 0
select a.* from # a left join # b on a.id=b.id-1 left join # c on a.id=c.id+1
where a.status<>isnull(b.status,~a.status) or a.status<>isnull(c.status,~a.status)
/*
id status
----------- -----------
1 1
3 1
4 0
5 0
6 1
7 0
10 0
11 1
12 0
16 0
*/
服务器: 消息 156,级别 15,状态 1,行 2
在关键字 'with' 附近有语法错误。
服务器: 消息 195,级别 15,状态 1,行 4
'row_number' 不是可以识别的 函数名。
create table tb(id int,status int)
insert into tb
select 1 ,1 union all
select 2 ,1 union all
select 3 ,1 union all
select 4 ,0 union all
select 5 ,0 union all
select 6 ,1 union all
select 7 ,0 union all
select 8 ,0 union all
select 9 ,0 union all
select 10 ,0 union all
select 11 ,1 union all
select 12 ,0 union all
select 13 ,0 union all
select 14 ,0 union all
select 15 ,0 union all
select 16 ,0
go
with cte as
(
select *,rn = id - (row_number() over (partition by status order by id))
from tb
)
select *
from cte
where id in (select max(id) from cte group by rn
union all
select min(id) from cte group by rn)
order by id
drop table tb
/*
id status rn
----------- ----------- --------------------
1 1 0
3 1 0
4 0 3
5 0 3
6 1 2
7 0 4
10 0 4
11 1 6
12 0 5
16 0 5
(10 行受影响)