SQL:使用共享相同列值的另一个条目中的值更新每个条目

SQL:使用共享相同列值的另一个条目中的值更新每个条目,sql,sql-server,sql-update,subquery,Sql,Sql Server,Sql Update,Subquery,我有下表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:其中两个系

我有下表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:其中两个系统中的人员id始终相同


条件3可选:仅当只有一个收据类型=9时才执行此更新有时可能有3个或4个条目具有相同的人员id且为收据类型9

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

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;

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

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;
使用自联接:

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
)
WHERE子句的最后一部分带有且不存在。。。是三维可选条件。 请参阅带有自联接的简化。

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
)
WHERE子句的最后一部分带有且不存在。。。是三维可选条件。 请参阅一个简化的示例