如果两个列数据匹配,则从SQL表中删除1个重复行

时间:2016-04-15 16:51:29

标签: sql sql-server

我的表格中有三列

键名, 数, 数据

数据包含大量重复条目。如果" KeyName"我需要从表中的每个重复条目中删除1行。和"数据"重复。 我如何实现这一点是SQL查询。

2 个答案:

答案 0 :(得分:0)

您可以使用row_number()

为每对保留一行
with todelete as (
      select t.*,
             row_number() over (partition by keyname, data order by (select NULL)) as seqnum
      from t
     )
delete
from todelete
where seqnum > 1;

与任何此类操作一样,您应该在删除之前先检查。这很简单:

with todelete as (
      select t.*,
             row_number() over (partition by keyname, data order by (select NULL)) as seqnum
      from t
     )
select *
from todelete
where seqnum > 1;

答案 1 :(得分:0)

这应该这样做

WITH CTE
    AS (SELECT KeyName
            , Number
            , Data
            , [rn] = ROW_NUMBER() OVER(PARTITION BY KeyName
                                          , Data ORDER BY KeyName
                                                     , Data)
        FROM   yourtable)
     /* UNCOMMENT BELOW TO DELETE */
     --DELETE
    --FROM   CTE
    --WHERE  rn > 1;

    SELECT *
    FROM   CTE
    WHERE  rn > 1;