删除SQL

时间:2016-10-18 14:43:16

标签: sql

请您帮我解决这个重复输入问题?

我的表格中有列,如下所示;

**Date_time**           **Pro**                **Color**
2016-10-17              Basketball               Red
2016-10-17              Basketball               Red
2016-10-18              Hockey                   Silver
2016-10-18              Hockey                   Silver

我需要删除重复的条目并最终拥有;

**Date_time**           **Pro**                **Color**
2016-10-17      Basketball               Red
2016-10-18      Hockey                   Silver

我用这段代码得到了我想要的东西但是,我的尝试并没有成功。

DELETE FROM Sport WHERE date_time NOT IN (SELECT MIN(date_time)
    FROM sport GROUP BY date_time,pro,color) 

提前多多感谢。

2 个答案:

答案 0 :(得分:0)

据推测,你打算这样:

DELETE FROM Sport
    WHERE s.date_time > (SELECT MIN(s2.date_time)
                         FROM sport s2
                         WHERE s2.pro = sport.pro and s2.color = sport.color
                        );

实际上,如果您有多个重复的条目,那么上面只删除其中一个。尝试这样的事情:

DELETE FROM Sport
    WHERE s.date_time = (SELECT MAX(s2.date_time)
                         FROM sport s2
                         WHERE s2.pro = sport.pro and s2.color = sport.color
                        );

答案 1 :(得分:0)

WITH numbered AS (
    SELECT ROW_NUMBER() OVER(PARTITION BY [dupe-column-list] ORDER BY [dupe-column-list]) AS _dupe_num 
    FROM [table-name] 
    WHERE 1=1 -- any where clause if required
)
DELETE FROM numbered WHERE _dupe_num > 1;

上述查询将使用ROW_NUMBER()仅保留每条记录的首次出现。在您的情况下,[dupe-column-list]应包含您的所有列。