使用SQL INNER JOIN批量更新字段

时间:2016-08-20 02:34:30

标签: mysql sql sql-server inner-join

我有两张桌子发票和付款。发票有很多付款,我希望为所有发票行更新名为total_payments_amount的字段,并在单个SQL查询中为每个发票行添加所有相关付款的总和。所以这就是我试过的

UPDATE invoices
SET total_payments_amount = pays.total_amount
FROM invoices inv
INNER JOIN (
  SELECT invoice_id, SUM(amount) as total_amount
  FROM payments
  WHERE invoice_id IS NOT NULL
  GROUP BY invoice_id
) pays
ON inv.id = pays.invoice_id

但运行此查询后,我发现所有记录都包含相同的值。那么这里有什么不对?

1 个答案:

答案 0 :(得分:0)

尝试使用cte ..

;With cte_total
AS ( SELECT invoice_id, SUM(isnull(amount,0)) as total_amount
       FROM payments
       WHERE invoice_id IS NOT NULL
      GROUP BY invoice_id)
UPDATE inv
   SET inv.total_payments_amount = c.total_amount
FROM cte_total c
     JOIN invoices inv 
        ON inv.id = c.invoice_id