Northwind SQL每个客户的总订单数

时间:2017-05-20 10:48:13

标签: sql sql-server northwind

我已在TotalOrders表格中添加了一列Customers

ALTER TABLE customers ADD TotalOrders INT NULL

我正在尝试查找每个客户的订单总数,并将该值添加到此列,但是我无法弄清楚我需要准确汇总的内容

INSERT INTO customers (TotalOrders) SELECT SUM(...)

2 个答案:

答案 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