【问题标题】:Update multiple records using index result of sub-query使用子查询的索引结果更新多条记录
【发布时间】:2020-03-29 12:34:05
【问题描述】:

假设我有一个包含数据的表...

| person_id  |  priority  |
|------------|------------|
|    678     |     2      |
|    413     |     4      |
|    912     |     1      |
|    111     |     5      |

如何更新priority 以使值连续? ...

| person_id  |  priority  |
|------------|------------|
|    678     |     2      |
|    413     |     3      |    -- updated from 4 to 3
|    912     |     1      |
|    111     |     4      |    -- updated from 5 to 4

我知道我可以使用类似...

select
    row_number() over (order by [priority]) as position
from
    table_name

...查找一个人的“位置”,但我如何使用它来更新同一行?

priority 值应始终从 1 开始。

【问题讨论】:

    标签: sql tsql sql-update


    【解决方案1】:

    您可以使用可更新的 CTE 或子查询:

    with toupdate as (
          select t.*, row_number() over (order by [priority]) as new_priority
          from table_name
         )
    update toudpate
        set priority = new_priority
        where priority <> new_priority;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多