问题
I've added a column TotalOrders
to the Customers
table.
ALTER TABLE customers ADD TotalOrders INT NULL
I'm trying to find the total number of orders per customer and add that value to this column, however i can't figure out what do i need to sum exactly
INSERT INTO customers (TotalOrders) SELECT SUM(...)
回答1:
I think you should be using an update here. You can aggregate the total number of orders per customer in the orders
table, and then update the customers
table with this information.
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
回答2:
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
来源:https://stackoverflow.com/questions/44084941/northwind-sql-total-orders-per-customer