[英]INSERT a column into a table with SUM and GROUP BY
將按 ID 分組的計算列插入到 ID 匹配的另一列中的最佳方法是什么?
我有這個查詢:
SELECT DISTINCT cs.customerNumber, cs.totalOrderCost as paymentDue,
SUM(p.amount) as paymentMade
FROM customerSales cs LEFT OUTER JOIN payments p
ON cs.customerNumber = p.customerNumber
GROUP BY cs.customerNumber;
它返回 customerNumber、paymentDue、paymentMade,計算正確。
在表 customerSales 中,有兩列:customerNumber 和 totalOrderCost。 我想將“paymentMade”列(從支付列匯總並按 customerNumber 分組)添加到 customerSales 表中。
這種方法:
ALTER TABLE customerSales
ADD COLUMN paymentMade DECIMAL;
INSERT INTO customerSales(paymentMade)
SELECT SUM(p.amount) as paymentMade
FROM payments p
GROUP BY p.customerNumber;
給出錯誤“字段 customerNumber 沒有默認值”。
任何幫助,將不勝感激。 謝謝!
將列添加到表架構后:
ALTER TABLE customerSales ADD COLUMN paymentMade DECIMAL;
您應該使用基於子查詢的更新:
UPDATE customerSales
INNER JOIN (
SELECT DISTINCT cs.customerNumber
, cs.totalOrderCost as paymentDue
, SUM(p.amount) as paymentMade
FROM customerSales cs
INNER JOIN payments p ON cs.customerNumber = p.customerNumber
GROUP BY cs.customerNumber
) t ON customerSales.customerNumber =t.customerNumber
SET paymentMade = t.paymentMade
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.