【问题标题】:Update Missing Values更新缺失值
【发布时间】:2020-03-18 23:59:38
【问题描述】:

我有一个如下所示的数据集

|---------------------|------------------|------------------|
|      RowID          |     UserID       |      Code        |
|---------------------|------------------|------------------|
|       1             |         123      |        0         |
|---------------------|------------------|------------------|
|       2             |         123      |        0         |
|---------------------|------------------|------------------|
|       3             |         123      |        50        |
|---------------------|------------------|------------------|
|       4             |         456      |        0         |
|---------------------|------------------|------------------|
|       5             |         456      |        100       |
|---------------------|------------------|------------------|

我想将每个 UserID 的 0 更新为非 0 代码。有人可以提供帮助吗?

【问题讨论】:

    标签: sql sql-server tsql sql-update window-functions


    【解决方案1】:

    一个选项使用可更新的公用表表达式和窗口函数:

    with cte as (
        select code, max(code) over(partition by userID) max_code
        from mytable
    )
    update cte set code = max_code where code = 0
    

    【讨论】:

      【解决方案2】:

      您可以为此使用一个简单的子查询:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-14
        • 1970-01-01
        • 1970-01-01
        • 2022-08-02
        • 2023-02-16
        • 1970-01-01
        • 1970-01-01
        • 2021-09-17
        相关资源
        最近更新 更多