我编写了以下查询来获取客户电子邮件地址、订单计数(即客户下了多少订单)、订单的总价。但我得到了重复的结果。
我想要有不同的记录,例如:
Customer A, 5 orders, $125 total Customer B, 2 orders, $150 total
but i am getting the results like:
Customer A, 4 orders, $100 total Customer A, 1 order, $25 total Customer B, 1 order, $100 total Customer B, 1 order, $50 total
Can you please help me how can i get the result as i want. I have written the following Query:
Select
customers.CustomerID,
customers.EmailAddress,
COUNT(Orders.OrderID) AS Ordercount,
Sum(OrderDetails.TotalPrice * OrderDetails.Quantity) AS TotalPrice
from
customers
INNER JOIN Orders ON customers.CustomerID = Orders.CustomerID
INNER JOIN OrderDetails ON OrderDetails.OrderID = Orders.OrderID
GROUP BY
customers.CustomerID,
customers.EmailAddress,
Orders.OrderID,
OrderDetails.TotalPrice,
OrderDetails.Quantity
ORDER BY customers.CustomerID, orders.OrderID desc
最佳答案
您只需对选择中的字段进行分组,而不是 COUNT
或 SUM
的一部分
Select
customers.CustomerID,
customers.EmailAddress,
COUNT(Orders.OrderID) AS Ordercount,
Sum(OrderDetails.TotalPrice * OrderDetails.Quantity) AS TotalPrice
from
customers
INNER JOIN
Orders ON customers.CustomerID = Orders.CustomerID
INNER JOIN
OrderDetails ON OrderDetails.OrderID = Orders.OrderID
GROUP BY
customers.CustomerID,
customers.EmailAddress
ORDER BY
customers.CustomerID desc
关于sql - 获取sql中不同的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9191720/