【问题标题】:Update a column based on other rows column value根据其他行列值更新列
【发布时间】:2020-05-01 22:11:26
【问题描述】:

我有一张桌子,看起来像这样

   key fill store end_date    status
    1  123  1      2019-04-30  0  
    2  1234 1      2019-04-30  0
    3  123  1      2019-05-01  0

现在我需要更新第一条记录并设置status=1,因为第三条记录具有相同的填充、存储值并且是最新的。

输出:

   key fill store end_date    status
    1  123  1      2019-04-30  1  
    2  1234 1      2019-04-30  0
    3  123  1      2019-05-01  0

我尝试计算row_number 并尝试根据它更新列,但无法弄清楚如何在更新子句中使用结果。

update t set
  status = 1
from (
  select *
  from (
    select *
      , row_number() over (partition by fill, store order by end_dt desc) as row_num from t
    ) a
    where row_num = 2
  ) b

此查询正在更新所有记录,我的查询应进行哪些更改才能获得预期结果?

【问题讨论】:

    标签: sql sql-server database tsql sql-update


    【解决方案1】:

    我认为你想要:

    with cte as (
        select status, row_number() over(partition by fill, store order by end_date desc) rn
        from t
    )
    update cte set status = 1 where rn > 1
    

    在公用表表达式中,row_number() 对具有相同fillstore 的记录按降序排列end_date。然后,外部查询在未排名第一的行上将status 设置为1

    【讨论】:

      【解决方案2】:

      你可以做一个相关的子查询:

      update my_table a
      set status = 1
      where exists (
        select 1 
        from my_table b 
        where b.fill = a.fill 
          and b.store = a.store 
          and b.end_date > a.end_date
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-19
        • 2022-08-18
        • 1970-01-01
        • 1970-01-01
        • 2020-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多