mysql 编写一个SQL查询来计算每个客户的总购买量

wmtdaxz3  于 2023-05-05  发布在  Mysql
关注(0)|答案(3)|浏览(310)

我试图从W3 Schools上的在线数据库计算每个客户的总购买量
我使用的表是:
客户服务
订单
产品展示
订单详情
我的当前查询为我提供了客户的产品明智购买金额。我需要的是购买总额。

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;

我的输出:

我需要具有相同订单ID和客户ID的值的总和。
我尝试了group-by和sum,但它给了我所有产品的总和。

tv6aics1

tv6aics11#

你只需要一个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 s通常的写法。

67up9zun

67up9zun2#

如果需要具有相同订单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
yacmzcpb

yacmzcpb3#

这里是一个例子来实现&最终结果将包括客户ID,订单ID和计算的Total_Amount为每个组。

SELECT 
   cust.CustomerID,
   ord.OrderID,
   SUM(od.Quantity * pro.Price) as Total_Amount

FROM Customers cust, Orders ord, OrderDetails od, Products pro

WHERE
   cust.CustomerID = ord.CustomerID
   AND ord.OrderID = od.OrderID
   AND od.ProductID = pro.ProductID

GROUP BY
   cust.CustomerID,
   ord.OrderID;

相关问题