且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 SQL 表中删除重复行(基于多列的值)

更新时间:2022-04-24 22:20:15

Sample SQL FIDDLE

1) 使用 CTE 获取基于ARDivisionNo、CustomerNo 的最大船舶代码值记录对于每个客户

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) 要删除记录,请使用删除查询而不是选择并将 Where 子句更改为 rn > 1.示例 SQL FIDDLE

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;