删除t-sql中重复行的最简单方法

时间:2013-08-06 09:52:42

标签: tsql

在T-SQL查询中从表中删除重复项的最简单方法是什么?

列是A和B.

欢迎Oneliners。

4 个答案:

答案 0 :(得分:2)

这样的东西
DECLARE @TABLE TABLE(
        A VARCHAR(10),
        B VARCHAR(10)
)

INSERT INTO @TABLE VALUES
('1','1'),
('1','2'),
('2','2'),
('1','1'),
('1','2'),
('2','2')

SELECT  *
FROM    @TABLE

;WITH Vals AS (
        SELECT  *,
                ROW_NUMBER() OVER(PARTITION BY A,B ORDER BY A,B) ROWID
        FROM    @TABLE
)
DELETE
FROM    Vals
WHERE   ROWID > 1

SELECT  *
FROM    @TABLE

SQL Fiddle DEMO

答案 1 :(得分:2)

<强> how to remove duplicate values from MySQL table

DELETE a FROM tbl a
LEFT JOIN
(
    SELECT MIN(id) AS id, name
    FROM tbl
    GROUP BY name
) b ON a.id = b.id AND a.name = b.name
WHERE b.id IS NULL

答案 2 :(得分:1)

以下sql将完成这项工作

DECLARE @TEMP AS TABLE(a Varchar(100),b VarChar(100))

INSERT INTO @TEMP (a,b)
SELECT A,B FROM MY_Table
GROUP BY A, b

DELETE My_Table

INSERT INTO My_Table (a, b)
SELECT a, b
FROM @temp

SELECT * FROM My_Table

http://sqlfiddle.com/#!3/5fdb8/1

答案 3 :(得分:0)

试试这个

SELECT A, B, count(*)
FROM table
GROUP BY A, B
HAVING count(*) > 1