如何使用内部连接和聚合函数更新列?

How to update a column using inner join and aggregate function?

我正在尝试通过加入我的购物车 table 并计算购物车中所有商品的总和来更新我的订单 table 中所有订单的小计。这是我拥有的:

UPDATE O 
SET O.subtotal = ISNULL(SUM((C.price - C.discount_price) * C.qty), 0)
FROM Orders AS O
INNER JOIN Cart AS C ON O.cart_id = C.cart_id 
WHERE O.date > '01/01/2021'

但是我得到一个错误

An aggregate may not appear in the set list of an UPDATE statement

我怎样才能让上面的语句生效?

UPDATE 语句中,您不能使用以下聚合函数:SUM, GROUP BY

正确更新:

UPDATE  Orders   
SET 
    subtotal = C.sum_total 
FROM 
    Orders AS O
INNER JOIN (
    select 
        cart_id,  
        ISNULL(SUM((price - discount_price) * qty), 0) as sum_total 
    from Cart 
    group by 
        cart_id
) AS C ON O.cart_id = C.cart_id
WHERE O.date > '01/01/2021'