【问题标题】:Can`t correctly JOIN and GROUP BY无法正确 JOIN 和 GROUP BY
【发布时间】:2013-11-29 09:19:35
【问题描述】:

我的基本结构如下所示

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

我不明白错误在哪里。

【问题讨论】:

  • 谢谢,现在我正确地得到了 totalqty 列并且只有不同的 custid,但无论如何 numorders 是错误的((
  • 是的,见下文(您是在对您的 orderid 求和,而不是对它们进行计数)。

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


【解决方案1】:

应该这样做:

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;

【讨论】:

    【解决方案2】:

    在阅读更多内容后,您有两个问题。您正在汇总订单而不是计数,并且您正在按数量分组。 试试:

    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;
    

    【讨论】:

      猜你喜欢
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      • 1970-01-01
      • 2012-08-06
      • 2016-12-04
      • 1970-01-01
      • 2014-08-31
      相关资源
      最近更新 更多