【问题标题】:Delete Duplicate record in sql server if 2 colums matching如果 2 列匹配,则删除 sql server 中的重复记录
【发布时间】:2021-05-28 20:22:55
【问题描述】:
Col1 Col2 Col3
A B 1
A B 1
A B 2
A B 2
A c 1

当 col1 和 Col2 值相同而 Col3 值不同时,我不希望结果集中的值。 我想要的结果如下。我尝试了 row_number、group by ,但没有奏效。请在这里帮助我

Col1 Col2 Col3
A c 1

【问题讨论】:

标签: sql sql-server sql-server-2012


【解决方案1】:

你可以使用exists:

delete from t
    where exists (select 1
                  from t t2
                  where t2.col1 = t.col1 and t2.col2 = t.col1 and
                        t2.col3 <> t.col3
                 );

你也可以使用窗口函数:

with todelete as (
      select t.*,
             min(col3) over (partition by col1, col2) as min_col3,
             max(col3) over (partition by col1, col2) as min_col4
      from t
     )
delete from todelete
     where min_col3 <> max_col3;

【讨论】:

    【解决方案2】:

    最好的方法是使这些列成为唯一的复合键。但这里有一个查询,用于删除除您想要的结果之外的所有记录。

    delete from Table_1 
    where 
    Col1=(SELECT Col1
          FROM table_1
          GROUP BY Col1, Col2
          HAVING Count(*) > 1) 
    And 
    Col2 =(SELECT Col2
           FROM table_1
           GROUP BY Col1, Col2
           HAVING Count(*) > 1)
    

    这可能不是最优化和最有效的查询,但它确实有效。如果您不想删除重复记录而只检索唯一记录:

    SELECT Col1,Col2
    FROM table_1
    GROUP BY Col1, Col2
    HAVING Count(*) = 1
    

    获取重复记录:

    SELECT Col2,Col1
    FROM table_1
    GROUP BY Col1, Col2
    HAVING Count(*) > 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 1970-01-01
      • 2016-08-07
      • 2021-11-12
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多