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

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

I have following SQL table:

AR_Customer_ShipTo

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


        
4条回答
  •  萌比男神i
    2020-12-03 10:31

    ROW_NUMBER() is great for this:

    ;WITH cte AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY ARDivisionNo,CustomerNo ORDER BY ShipToCode DESC) AS RN 
                  FROM AR_Customer_ShipTo
                  )
    SELECT * 
    FROM  cte
    WHERE RN = 1
    

    You mention removing the duplicates, if you want to DELETE you can simply:

    ;WITH cte AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY ARDivisionNo,CustomerNo ORDER BY ShipToCode DESC) AS RN 
                  FROM AR_Customer_ShipTo
                  )
    DELETE cte
    WHERE RN > 1
    

    The ROW_NUMBER() function assigns a number to each row. PARTITION BY is optional, but used to start the numbering over for each value in a given field or group of fields, ie: if you PARTITION BY Some_Date then for each unique date value the numbering would start over at 1. ORDER BY of course is used to define how the counting should go, and is required in the ROW_NUMBER() function.

提交回复
热议问题