开发者

How to delete duplicates from a table and keeping only the one with highest id in sql server?

开发者 https://www.devze.com 2023-03-11 00:54 出处:网络
I have a table with unique ID and then some fields. I would like to delete all the dupliacte rows and keep only one, the one with highest id.

I have a table with unique ID and then some fields. I would like to delete all the dupliacte rows and keep only one, the one with highest id.

For example assuming to have a table with 3 fields: RECORD_ID, FIELD_ONE, FIELD_TWO

which is the query that allows me to delete all records that have same value for FIELD_ONE and 开发者_运维问答FIELD_TWO except the one that has highest RECORD_ID?


Found:

with cte
as
(
    select *, row_number() over(partition by FIELD_ONE, FIELD_TWO order by RECORD_ID desc) RowNumber
    from TestTable
)
delete cte
where RowNumber > 1
0

精彩评论

暂无评论...
验证码 换一张
取 消