(SQL) 如何将 "Total Quantity" 个值聚合到一个 "Customer Name"

(SQL) How to aggregate "Total Quantity" values under one "Customer Name"

所以我有这个简单的查询

SELECT C.CustomerName, (P.Price * OD.Quantity) AS TotalQuantity, 
FROM Customers as C
INNER JOIN Orders AS O
ON C.CustomerID = O.CustomerID
INNER JOIN OrderDetails AS OD
ON O.OrderID = OD.OrderID
INNER JOIN Products AS P
ON OD.ProductID = P.ProductID
ORDER BY TotalQuantity DESC;

这是结果

CustomerName    TotalQuantity
Piccolo und mehr    13175
Simons bistro   13175
Mère Paillarde  12911.5
Queen Cozinha   10540
Split Rail Beer & Ale   5270
Ernst Handel    5270
Blondel père et fils    4332.650000000001
Frankenversand  3850
Ernst Handel    3850
Save-a-lot Markets  3512
Rattlesnake Canyon Grocery  3451
Suprêmes délices    3240
Old World Delicatessen  3094.75
Save-a-lot Markets  2970.96
Save-a-lot Markets  2880

如您所见,“节省大量市场”分为三个记录。我的代码所做的是将每个单独订单的总产品数量乘以价格。我需要做的是汇总每个客户的所有订单,因此这将是“Save-a-lot Markets”的一条记录,总数量为 9,362.96。

您对如何实现这一点有什么想法吗?

抱歉,我的解释很草率。

您必须使用聚合函数 sumgroup by

SELECT 
   C.CustomerName, 
   SUM(P.Price * OD.Quantity) AS TotalQuantity, 
FROM Customers as C
INNER JOIN Orders AS O
ON C.CustomerID = O.CustomerID
INNER JOIN OrderDetails AS OD
ON O.OrderID = OD.OrderID
INNER JOIN Products AS P
ON OD.ProductID = P.ProductID
GROUP BY 
    C.CustomerName
ORDER BY 
    TotalQuantity DESC;

听起来你想要聚合。注意 GROUP BYSUM():

SELECT C.CustomerName, SUM(P.Price * OD.Quantity) AS TotalQuantity, 
FROM Customers aC INNER JOIN
     Orders O
     ON C.CustomerID = O.CustomerID INNER JOIN 
     OrderDetails OD
     ON O.OrderID = OD.OrderID INNER JOIN 
     Products AS P
     ON OD.ProductID = P.ProductID
GROUP BY C.CustomerName
ORDER BY TotalQuantity DESC;