[英]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.