表 TableA 中有列 C1 和 C2 ,现在需要删除该表中满足以下条件的数据:
C2 相同的数据,其对应的 C1 都为 1
比如:
ID C1 C2
0 0 1
1 1 1
2 1 2
3 0 2
4 1 3
5 1 3
只有最后两列可以删掉
如何使用一条表达式一次性完成?
------解决思路----------------------

--路过写个玩玩,好久没写了
create table tableA(id int identity(1,1),C1 int,C2 int)
insert tableA(C1,C2) select 0,1
insert tableA(C1,C2) select 1,1
insert tableA(C1,C2) select 1,2
insert tableA(C1,C2) select 0,2
insert tableA(C1,C2) select 1,3
insert tableA(C1,C2) select 1,3
insert tableA(C1,C2) select 1,4
select * from tableA
delete A
from tableA as A
where not exists(select 1 from tableA where C2=A.C2 and C1<>1)
and (select count(*) from tableA where C2=A.C2)>1 -- 只有1笔不删
drop table tableA
------解决思路----------------------
DELETE t1
FROM tableA t1,#ableA t2
WHERE t1.id!=t2.id AND t1.C2=t2.C2 AND t1.C1 = t2.C1 AND t1.C1 = 1
------解决思路----------------------
借用#1的数据,一次性统计比逐个做子查询效率更高
DELETE FROM tableA
FROM tableA a,
(
SELECT C2
FROM tableA
GROUP BY C2
HAVING COUNT(*) = SUM(C1)
AND COUNT(*) <> 1 -- 如果只有一个1也删去掉这个条件
) b
WHERE a.C2 = b.C2
SELECT * FROM tableA
id C1 C2
----------- ----------- -----------
1 0 1
2 1 1
3 1 2
4 0 2
7 1 4
------解决思路----------------------
-- 借1 楼的数据,凑个人数
;with m as (
select * ,
ROW_NUMBER() over (partition by c2 order by case when c1 = 1 then 1 end desc) rn
from tableA
)
delete m where rn > 1
go