假设我在sql server 2008中有一个下表。
Column1 Column2 Column3
1 2 1
1 2 1
5 1 1
3 2 1
3 2 1
4 1 1
输出应该是
Column1 Column2 Column3
5 1 1
4 1 1
如果某行存在重复项,则原始行和所有重复行将被删除。如果一行没有任何重复项。然后它被保留。我怎样才能做到这一点?
答案 0 :(得分:1)
试试这个,
DECLARE @Table TABLE (
Column1 INT
,Column2 INT
,Column3 INT
)
INSERT INTO @Table
(Column1,Column2,Column3)
VALUES
(1,2,1),
(1,2,1),
(5,1,1),
(3,2,1),
(3,2,1),
(4,1,1)
SELECT *
FROM @Table
DELETE t1
FROM @Table t1
INNER JOIN (
SELECT Column1
,Column2
,Column3
FROM @Table t
GROUP BY Column1
,Column2
,Column3
HAVING count(*) > 1
) t2 ON t1.column1 = t2.Column1
AND t1.column2 = t2.column2
AND t1.column3 = t2.column3
SELECT * FROM @Table