How to update distinct column in SQL Server 2005?

时光总嘲笑我的痴心妄想 提交于 2020-01-06 15:17:42

问题


In my table I have a column Segment_No which has duplicates. Now I want to update those duplicates.

For example: the value 249X5601 is present in two rows. I want to change the second value to 249X5601R


回答1:


The general form would be as follows:

;with AllRows as (
    select Donation_ID,Registration_No,Segment_No,
           ROW_NUMBER() OVER (
               PARTITION BY Segment_No
               order by <Suitable_Column>
           ) as rn
    from UnnamedTable
)
update AllRows set Segment_no = <New_Value>
where rn > 1

Where <Suitable_Column> gives the column(s) the define which row is "first" and which is second. <New_Value> defines how the new Segment_no value should be computed, and rn gives the row numbers - so the where clause is ignoring the "first" row.

So if there are only ever a max of two rows sharing a single Segment_no value, and the "first" is the one with the lowest Donation_ID value, then it would be:

;with AllRows as (
    select Donation_ID,Registration_No,Segment_No,
           ROW_NUMBER() OVER (
               PARTITION BY Segment_No
               order by Donation_ID
           ) as rn
    from UnnamedTable
)
update AllRows set Segment_no = Segment_no + 'R'
where rn > 1


来源:https://stackoverflow.com/questions/19488352/how-to-update-distinct-column-in-sql-server-2005

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!