34,873
社区成员
发帖
与我相关
我的任务
分享if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([value1] int,[value2] int)
insert [tb]
select 1,12 union all
select 1,13 union all
select 1,23 union all
select 0,14 union all
select 0,15 union all
select 1,16 union all
select 0,23 union all
select 0,22 union all
select 1,21 union all
select 1,12
select id=identity(int,1,1),* into # from tb
select * into #1 from # t where not exists(select 1 from # where value1=t.value1 and id=t.id-1)
select * into #2 from # t where not exists(select 1 from # where value1=t.value1 and id=t.id+1)
select
a.*,
b.px
into #3
from
# a,
(select
a.id as id1,
b.id as id2,
a.px
from
(select *,px=(select count(1)+1 from #1 where id<t.id) from #1 t) a,
(select *,px=(select count(1)+1 from #2 where id<t.id) from #2 t) b
where
a.px=b.px) b
where a.id between b.id1 and b.id2
select
value1,
value2,
col=(select count(1)+1 from #3 where px=t.px and id<t.id)
from
#3 t
drop table #,#1,#2,#3
/**
value1 value2 col
----------- ----------- -----------
1 12 1
1 13 2
1 23 3
0 14 1
0 15 2
1 16 1
0 23 1
0 22 2
1 21 1
1 12 2
(所影响的行数为 10 行)
**/declare @t table( value1 int,value2 int)
insert into @t
select 1,12 union all
select 1,13 union all
select 1,23 union all
select 0,14 union all
select 0,15 union all
select 1,16 union all
select 0,23 union all
select 0,22 union all
select 1,21 union all
select 1,21
;
with cte1 as
(
select id=row_number() over (order by getdate()),* from @t
)
,
cte2 as
(
SELECT *,flag = (SELECT COUNT(*) FROM cte1
WHERE id < t.id AND value1<>t.value1) from cte1 t
)
select value1,value2 from cte2 c2
where not exists (select 1 from cte2 where value1=c2.value1 and flag=c2.flag and id<c2.id)
/*
value1 value2
----------- -----------
1 12
0 14
1 16
0 23
1 21
(5 行受影响)
*/---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([value1] int,[value2] int)
insert [tb]
select 1,12 union all
select 1,13 union all
select 1,23 union all
select 0,14 union all
select 0,15 union all
select 1,16 union all
select 0,23 union all
select 0,22 union all
select 1,21 union all
select 1,12
---查询---
select id=identity(int,1,1),* into # from [tb]
select value1,value2 from # t where not exists(select * from # where value1=t.value1 and id=t.id-1)
---结果---
value1 value2
----------- -----------
1 12
0 14
1 16
0 23
1 21
(所影响的行数为 5 行)