将具有特定值的列更新为具有相同ID的列值

时间:2015-09-07 13:09:20

标签: sql sql-server sql-update

我的表:

 ID | Number
-------------------
| 1 | 0x
| 1 | 12345678
| 1 | 12345678
| 2 | 0x
| 2 | 0x
| 2 | 242424
| 3 | 88888
| 3 | 88888
| 4 | 0x
| 4 | 0x

必须更新表,以便每个'0x'都会更新为正确的'Number'(如果存在)。

需要的结果:

ID | Number
-------------------
| 1 | 12345678      <-- Updated
| 1 | 12345678
| 1 | 12345678
| 2 | 242424        <-- Updated
| 2 | 242424        <-- Updated
| 2 | 242424
| 3 | 88888         <- No change on id = 3
| 3 | 88888         <- No change on id = 3
| 4 | 0x            <- No change because there's no relevant 'Number' to update 
| 4 | 0x            <- No change because there's no relevant 'Number' to update 

1 个答案:

答案 0 :(得分:3)

Demo of the following query

;WITH CTE AS (
    SELECT Id, Max(number) Number
    FROM YourTable
    WHERE Number <> '0x'
    GROUP BY Id
)
UPDATE ut SET Number = c.Number
FROM YourTable ut
    JOIN CTE c ON ut.Id = c.Id
WHERE ut.Number = '0x'