22,209
社区成员
发帖
与我相关
我的任务
分享
;WITH CTE (ID,subnumber,TYPE)
AS(
select 1,'a',1
Union ALL select 2,'a',6
Union ALL select 3,'b',1
Union ALL select 4,'b',1
Union ALL select 5,'c',1
Union ALL select 6,'d',1
Union ALL select 7,'d',2
Union ALL select 8,'d',2
)
SELECT *
FROM CTE a
WHERE NOT EXISTS(SELECT * FROM CTE WHERE TYPE = 1 AND CTE.subnumber = a.subnumber AND ID > a.ID)
if OBJECT_ID('tempdb..#a') is not null drop table #a
;with a(ID,subnumber,type) as (
select 1,'a',1 union all
select 2,'a',6 union all
select 3,'b',1 union all
select 4,'b',1 union all
select 5,'c',1 union all
select 6,'d',1
)
select * into #a from a
delete a from #a as a
where a.ID in(
select t.id from (select *,ROW_NUMBER()over(partition by subnumber,type order by id desc) as rn from #a) t where rn>1
)
select * from #a
/*
ID subnumber type
1 a 1
2 a 6
4 b 1
5 c 1
6 d 1
*/