0

我的基本结构如下

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

我无法理解错误在哪里。

4

2 回答 2

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;
于 2013-11-15T20:49:11.997 回答
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;
于 2013-11-15T20:49:52.903 回答