【问题标题】:SQL: Update every entry with value from another entry that share same column valueSQL:使用共享相同列值的另一个条目的值更新每个条目
【发布时间】:2019-12-20 11:28:41
【问题描述】:

我有下表 trn_ReceiptLog

我想知道如果条目 #1 的数量为 0,是否可以将条目 #1 的数量更新为与条目 #2 相同?

我有超过 5000 个条目需要更新,基本上是这样的:

UPDATE trn_ReceiptLog SET amount = (SELECT amount FROM trn_ReceiptLog WHERE receipt_type = 0) WHERE amount = 0

但我不确定如何单独为所有条目执行此操作,我需要某种循环吗?

条件 1:收据类型将始终为需要从中提取金额的类型的 0。

条件 2:person_id 在其中两个中始终相同。

条件3(可选):仅当只有一个receipt_type = 9时才执行此更新(有时可能有3或4个具有相同person_id且receipt_type为9的条目

【问题讨论】:

    标签: sql sql-server sql-update subquery


    【解决方案1】:

    您可以使用窗口函数来计算条件所需的信息。那么逻辑很简单:

    with toupdate as (
          select t.*,
                 max(case when receipt_type = 9 then amount else 0 end) over (partition by person_id) as amount_9,
                 sum(case when receipt_type = 9 then 1 else 0 end) over (partition by person_id) as num_9s
          from t
         )
    update toupdate
        set amount = amount_9
        where receipt_type = 0;
    

    【讨论】:

      【解决方案2】:

      使用自联接:

      update t
      set t.amount = tt.amount
      from trn_ReceiptLog t inner join trn_ReceiptLog tt
      on tt.person_id = t.person_id
      where t.receipt_type = 9 and tt.receipt_type = 0 and t.amount = 0
      and not exists (
        select 1 from trn_ReceiptLog
        where entry_id <> t.entry_id and person_id = t.person_id and receipt_type = 9
      )
      

      带有AND NOT EXISTS...WHERE 子句的最后一部分是3d 可选条件。
      查看简化的demo

      【讨论】:

        猜你喜欢
        • 2021-11-06
        • 2019-05-04
        • 1970-01-01
        • 2022-08-17
        • 2017-12-17
        • 2013-01-27
        • 2017-05-04
        • 2019-09-11
        • 1970-01-01
        相关资源
        最近更新 更多