我有这样的表:
Col1 | Col2
AAA | 1
BBB | X
AAA | X
CCC | 1
我想找到基于Col1的重复项。然后我想留下在Col2中有'X'的行并删除另一行。
我找到了如何找到重复项:
SELECT col1, col2, col3=count(*)
INTO holdkey
FROM t1
GROUP BY col1, col2
HAVING count(*) > 1
但是这个例子进一步说明了如何删除相同的行而不是如何选择一行。
不过,这是mssql2000答案 0 :(得分:1)
这可以很好地利用可更新的CTE和窗口函数:
with todelete as (
select t1.*, count(*) over (partition by col1) as cnt
from t1
)
delete from todelete
where cnt > 1 and col2 <> 'X';
答案 1 :(得分:1)
假设该表名为test,这应该可行。我刚尝试过: - )
DELETE From test WHERE Col1 IN(
SELECT Col1 FROM test
GROUP BY Col1
HAVING COUNT(1) > 1)
AND Col2 = '1'
答案 2 :(得分:0)
DELETE tbl1 FROM t1 AS tbl1
CROSS APPLY (
SELECT TOP 1 tbl2.col1
FROM t1 AS tbl2
WHERE tbl1.col1 = tbl2.col1
GROUP BY tbl2.col1
HAVING COUNT(*) > 1
) t2
WHERE tbl1.col2 != 'X'
答案 3 :(得分:0)
是否存在Col1重复的情况,但实例没有col2 ='x'。如果您遇到这种情况,您将从表中丢失该值。
select col1
into tmp
from t1
group by t1
having count(*)>1;
delete from t1
where col1 in (select col1 from tmp)
and col2<>'X';
Drop table tmp;