Question

I have base structure as given below

Sales.Customers    Sales.Orders    Sales.OrderDetails
---------------    ------------    ------------------
country            orderid          orderid
custid             custid           qty

So I need return United States customers, and for each customer return the total number of orders and total quantities. I wrote such query:

SELECT
C.custid, SUM(O.orderid) as numorders,
SUM(OD.qty) as totalqty

FROM Sales.Customers AS C
JOIN Sales.Orders AS O
ON C.custid = O.custid
    JOIN Sales.OrderDetails AS OD
    ON O.orderid = OD.orderid

WHERE country = 'USA'
GROUP BY C.custid;

Unfortunately I get such result:

custid      numorders   totalqty
----------- ----------- -----------
32          235946      345
36          94228       122
43          21027       20
.......     .....      ....

Instead of

custid      numorders    totalqty
----------- ----------- -----------
32          11            345
36          5             122

I can`t understand where mistake is.

Was it helpful?

Solution

This should do:

SELECT  C.custid, 
        COUNT(DISTINCT O.orderid) as numorders,
        SUM(OD.qty) as totalqty
FROM Sales.Customers AS C
INNER JOIN Sales.Orders AS O
    ON C.custid = O.custid
INNER JOIN Sales.OrderDetails AS OD
    ON O.orderid = OD.orderid
WHERE country = 'USA'
GROUP BY C.custid
ORDER BY C.custid;

OTHER TIPS

Upon a bit more reading, you have two things wrong. You're summing orders instead of counting, and you're grouping on quantity. Try:

SELECT
C.custid, 
COUNT(distinct O.orderid) as numorders,
SUM(OD.qty) as totalqty

FROM Sales.Customers AS C
JOIN Sales.Orders AS O
ON C.custid = O.custid
    JOIN Sales.OrderDetails AS OD
    ON O.orderid = OD.orderid

WHERE country = 'USA'
GROUP BY C.custid
ORDER BY C.custid;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top