How to update distinct column in SQL Server 2005?

2019-09-15 03:38发布

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

Table

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

1条回答
2楼-- · 2019-09-15 04:03

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
查看更多
登录 后发表回答