无法正确加入和GROUP BY

时间:2013-11-15 20:45:56

标签: sql sql-server tsql sql-server-2014

我的基础结构如下所示

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

所以我需要返回美国客户,并为每位客户退回订单总数和总数量。我写了这样的查询:

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;

不幸的是我得到了这样的结果:

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

而不是

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

我无法理解错误在哪里。

2 个答案:

答案 0 :(得分:4)

这应该做:

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;

答案 1 :(得分:1)

多读一读,你有两件事是错的。你在汇总订单而不是计算,而你正在按数量进行分组。 尝试:

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;