编写SQL查询以计算每个客户的总购买金额

时间:2019-11-29 13:00:15

标签: mysql sql group-by

我正在尝试从W3 Schools的在线数据库中计算每个客户的总购买金额

我正在使用的表是:

  

客户

     

订单

     

产品

     

OrderDetails

我当前的查询为我提供了针对客户的产品明智的购买金额。我需要的是总购买金额。

SELECT c.CustomerID,o.OrderID,(ord.Quantity*p.Price) as 
Total_Amount
from Customers c inner join Orders o
inner join Products p
inner join OrderDetails ord
on c.CustomerID = o.CustomerID
and o.OrderID = ord.OrderID
and ord.ProductID = p.ProductID;
  

我的输出:

Output

我需要具有相同订单ID和客户ID的值的总和。

我尝试了分组和求和,但它给了我所有产品的总和。

2 个答案:

答案 0 :(得分:1)

您只需要GROUP BY

SELECT c.CustomerID, SUM(ord.Quantity*p.Price) as 
Total_Amount
FROM Customers c inner join Orders o
     on c.CustomerID = o.CustomerID join
     OrderDetails ord
     on o.OrderID = ord.OrderID join
     Products p
     on ord.ProductID = p.ProductID
GROUP BY CustomerID;

请注意,这对JOIN进行排序,因此ON子句是交错的。 JOIN通常是这样写的。

答案 1 :(得分:0)

如果需要具有相同订单ID和客户ID的值的总和,则需要根据客户ID和订单ID来对行进行分组。

SELECT c.CustomerID,o.OrderID,SUM(ord.Quantity*p.Price) as Total_Amount
from Customers c inner join Orders o
inner join Products p
inner join OrderDetails ord
on c.CustomerID = o.CustomerID
and o.OrderID = ord.OrderID
and ord.ProductID = p.ProductID
Group By c.CustomerID,o.OrderID