如何获取Qty * Price
中的#OrderDetail
到TotalCost
的{{1}}列中。
订购
#Order
OrderDetail
ID | TotalCost
1 | 100
我尝试了以下查询,但是它给了我以上结果。
OrderID | BasePrice | QtyOrdered
1 | 100.00 | 1
1 | 50.00 | 3
结果应为(100 * 1)+(50 * 3)= 250
是否可以在不使用内部查询或表变量的情况下实现这一目标?
答案 0 :(得分:2)
您需要先汇总才能加入:
UPDATE o
SET TotalCost = od.cost
FROM o JOIN
(SELECT od.OrderID, SUM(od.QtyOrdered * od.BasePrice) as cost
FROM #OrderDetails od
GROUP BY od.OrderID
) od
ON od.OrderID = o.ID;
答案 1 :(得分:1)
您可以使用subquery
:
UPDATE o
SET o.TotalCost = (SELECT SUM(od.BasePrice * od.QtyOrdered)
FROM #OrderDetails od
WHERE od.OrderID = o.ID)
FROM #Order o;
答案 2 :(得分:0)
尝试这样的事情:
;WITH CTE AS(
SELECT OrderID ,SUM(baseprice * QtyOrdered) as totalPrice
FROM #OrderDetails
GROUP BY OrderID
)
UPDATE o
SET o.TotalCost = CTE.TotalPrice
FROM #Order INNER JOIN CTE ON CTE.OrderID = o.ID