22,298
社区成员
发帖
与我相关
我的任务
分享DELETE t2
FROM (SELECT *,Grp2=ROW_NUMBER()OVER(PARTITION BY ID,Grp ORDER BY 时间)%COUNT(*)OVER(PARTITION BY ID,Grp) FROM (Select *,Grp=ROW_NUMBER()OVER(PARTITION BY ID ORDER BY [时间])-ROW_NUMBER()OVER(PARTITION BY ID,[标识] ORDER BY 时间) from #原始数据) t1 ) AS t2
WHERE Grp2 NOT IN(0,1) AND [标识]=0
加上AND [标识]=0use Tempdb
go
--> --> 中国风(Roy)生成測試數據
if not object_id(N'Tempdb..#原始数据') is null
drop table #原始数据
Go
Create table #原始数据([ID] int,[时间] nvarchar(24),[标识] int)
Insert #原始数据
select 1,N'0000',0 union all
select 1,N'0002',1 union all
select 2,N'0007',1 union all
select 2,N'0005',0 union all
select 1,N'0001',1 union all
select 2,N'0003',0 union all
select 1,N'0003',0 union all
select 1,N'0005',0 union all
select 2,N'0006',0 union all
select 2,N'0001',1 union all
select 2,N'0004',0 union all
select 1,N'0004',1 union all
select 1,N'0007',0 union all
select 1,N'0006',0 union all
select 2,N'0002',0
Go
DELETE t2 FROM (SELECT *,Grp2=ROW_NUMBER()OVER(PARTITION BY ID,Grp ORDER BY 时间)%COUNT(*)OVER(PARTITION BY ID,Grp) FROM (Select *,Grp=ROW_NUMBER()OVER(PARTITION BY ID ORDER BY [时间])-ROW_NUMBER()OVER(PARTITION BY ID,[标识] ORDER BY 时间) from #原始数据) t1 ) AS t2 WHERE Grp2 NOT IN(0,1)
SELECT * FROM #原始数据 ORDER BY 1,2
/*
ID 时间 标识
1 0000 0
1 0001 1
1 0002 1
1 0003 0
1 0004 1
1 0005 0
1 0007 0
2 0001 1
2 0002 0
2 0006 0
2 0007 1
*/
select a.id,a.时间,a.标识,b.标识,c.标识 from table a left join table b on a.id=b.id and cast(a.时间 as int)=cast(b.时间 as int)-1
left join table c on a.id=b.id and cast(a.时间 as int)=cast(c.时间 as int)+1
where a.标识=0 and b.标识=0 and c.标识=0