在sql中获取不同的记录

时间:2012-02-08 10:41:35

标签: sql

我写了一个以下查询来获取客户电子邮件地址,订单数量是客户订购的订单数量,订单的总价格。但我得到了重复的结果。

我希望有不同的记录,如:

Customer A, 5 orders, $125 total
Customer B, 2 orders, $150 total

但我得到的结果如下:

Customer A, 4 orders, $100 total
Customer A, 1 order, $25 total
Customer B, 1 order, $100 total
Customer B, 1 order, $50 total

你能帮我帮我怎样才能得到我想要的结果。我写了以下查询:

    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

3 个答案:

答案 0 :(得分:1)

问题仍在GROUP BY部分,请尝试这样:

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, COUNT(Orders.OrderID) desc

答案 1 :(得分:1)

您只需group by COUNTSUM

中选择而非部分的字段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
{{1}}

答案 2 :(得分:1)

按订单ID等列进行分组和排序是问题 - 尝试:

Select customers.CustomerID,
       max(customers.EmailAddress) AS 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
ORDER BY customers.CustomerID