Update column with certain value to a column value with same id

我只是一个虾纸丫 提交于 2019-12-24 04:36:12

问题


My Table:

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

Table must be updated so that every '0x' will be updated to a correct 'Number' if there exists one.

Result needed:

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:


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'


来源:https://stackoverflow.com/questions/32439575/update-column-with-certain-value-to-a-column-value-with-same-id

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