我有一个类似于以下内容的数据集
|---------------------|------------------|------------------|
| RowID | UserID | Code |
|---------------------|------------------|------------------|
| 1 | 123 | 0 |
|---------------------|------------------|------------------|
| 2 | 123 | 0 |
|---------------------|------------------|------------------|
| 3 | 123 | 50 |
|---------------------|------------------|------------------|
| 4 | 456 | 0 |
|---------------------|------------------|------------------|
| 5 | 456 | 100 |
|---------------------|------------------|------------------|
我想将每个UserID的0更新为非0代码。有人可以为此提供协助吗?
答案 0 :(得分:4)
一个选项使用可更新的公用表表达式和窗口函数:
with cte as (
select code, max(code) over(partition by userID) max_code
from mytable
)
update cte set code = max_code where code = 0
答案 1 :(得分:1)
您可以为此使用一个简单的子查询:
update MyTable set
/* If its possible that a user might have multiple Codes which are non-zero you adjust the sub-query to return the correct one */
Code = (select top 1 Code from MyTable T2 where Code != 0 and T2.UserID = MyTable.UserId)
where Code = 0