删除反转的重复项 - SQL Server

时间:2013-11-05 07:16:09

标签: sql sql-server

我想删除重复项,但它们不会显示为重复项。 是否有一个查询来帮助删除它只能留下一个?

enter image description here

2 个答案:

答案 0 :(得分:2)

此查询将生成规范化值(如果它们都是varchars),您现在可以检查重复项

select 
    [someId], 
    case 
       when reg_num < driver_name then reg_num + driver_name 
                                  else driver_name + reg_num 
    end as combination

答案 1 :(得分:0)

这样的事情将按排序顺序按两个字段对行进行分组,并删除除一个之外的所有字段。 我假设两个字段必须匹配,并且您有一个名为TableId的主键。

DELETE
    T
FROM
    [Table] T
JOIN (
    SELECT
        TableId,
        [Name],
        ROW_NUMBER() OVER ( PARTITION BY [Name] ORDER BY TableId DESC ) RowId
    FROM (
        SELECT
            TableId,
            Reg_Num + '|' + Driver_Name AS [Name]
        FROM
            [Table]
        WHERE
            Reg_Num <= Driver_Name
        UNION
        SELECT
            TableId,
            Driver_Name + '|' + Reg_Num AS [Name]
        FROM
            [Table]
        WHERE
            Driver_Name < Reg_Num
        ) Y
    ) X ON
        X.TableId = T.TableID
WHERE
    RowId > 1