我已在TotalOrders
表格中添加了一列Customers
。
ALTER TABLE customers ADD TotalOrders INT NULL
我正在尝试查找每个客户的订单总数,并将该值添加到此列,但是我无法弄清楚我需要准确汇总的内容
INSERT INTO customers (TotalOrders) SELECT SUM(...)
答案 0 :(得分:2)
我认为你应该在这里使用更新。您可以在orders
表中汇总每个客户的订单总数,然后使用此信息更新customers
表。
UPDATE t1
SET TotalOrders = t2.TotalOrders
FROM customers t1
INNER JOIN
(
SELECT CustomerID, COUNT(*) AS TotalOrders
FROM orders
GROUP BY CustomerID
) t2
ON t1.CustomerID = t2.CustomerID
答案 1 :(得分:1)
INSERT INTO customers (TotalOrders)
VALUES(SELECT SUM(Orders.Total)
FROM Orders INNER JOIN Customers ON Orders.CustomerId=
Customer.Id Group By Customer.Id) WHERE Customer.Id =Orders.CustomerId