Removing duplicate rows (based on values from multiple columns) from SQL table

后端 未结 4 883
春和景丽
春和景丽 2020-12-03 10:14

I have following SQL table:

AR_Customer_ShipTo

+--------------+------------+-------------------+------------+
| ARDivisionNo | Custo         


        
4条回答
  •  星月不相逢
    2020-12-03 10:23

    Sample SQL FIDDLE

    1) Use CTE to get max ship code value record based on ARDivisionNo, CustomerNo for each Customers

    WITH cte AS (
      SELECT*, 
         row_number() OVER(PARTITION BY ARDivisionNo, CustomerNo ORDER BY ShipToCode desc) AS [rn]
      FROM t
    )
    Select * from cte WHERE [rn] = 1
    

    2) To Delete the record use Delete query instead of Select and change Where Clause to rn > 1. Sample SQL FIDDLE

    WITH cte AS (
      SELECT*, 
         row_number() OVER(PARTITION BY ARDivisionNo, CustomerNo ORDER BY ShipToCode desc) AS [rn]
      FROM t
    )
    Delete from cte WHERE [rn] > 1;
    
    select * from t;
    

提交回复
热议问题