Northwind SQL total orders per customer

穿精又带淫゛_ 提交于 2020-01-07 04:20:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!