2

使用这个查询,我得到了我需要的每个客户下了多少订单的结果。但是,当我在 SELECT 字段中使用 SUM(OrderLine.ActualPrice) 并使用内部联接将 Order 表链接到包含价格的 OrderLine 表时。COUNT 结果有偏差,因为 OrderLine 表包含同一个 Order 的多个 OrderNo,因为一个订单可以包含多个产品。

如何将 COUNT 保留为我使用此查询获得的结果,同时输入他们订单的总购买量的 SUM 查询?

SELECT C.custno, 
       companyname, 
       Count(customerorder.orderno)AS 'Total Orders', 
FROM   customer C 
       INNER JOIN customerorder 
               ON customerorder.custno = C.custno 
GROUP  BY C.custno, 
          companyname 

修改后的查询结果不正确

SELECT C.custno, 
       companyname, 
       Count(customerorder.orderno)AS 'Total Orders', 
       Sum(orderline.actualprice) 
FROM   customer C 
       INNER JOIN customerorder 
               ON customerorder.custno = C.custno 
       INNER JOIN orderline 
               ON customerorder.orderno = orderline.orderno 
GROUP  BY C.custno, 
          companyname 

这是我尝试使用并收到倾斜的 COUNT 结果的查询。

4

2 回答 2

2

你有两个基本的选择。

使用 DISTINCT

SELECT C.custno, 
       companyname, 
       Count(DISTINCT customerorder.orderno)AS 'Total Orders', 
       Sum(orderline.actualprice) 
FROM   customer C 
       INNER JOIN customerorder 
               ON customerorder.custno = C.custno 
       INNER JOIN orderline 
               ON customerorder.orderno = orderline.orderno 
GROUP  BY C.custno, 
          companyname 

笔记:

在对另一个问题的评论中,您说这仍然是结果。这似乎意味着相同的orderno内容可以出现在不止一个customerorder记录中。那是对的吗?


使用子查询使连接 1:1 而不是 1:many

SELECT C.custno, 
       companyname, 
       Count(customerorder.orderno)AS 'Total Orders', 
       Sum(orderline.actualprice) 
FROM   customer C 
       INNER JOIN customerorder 
               ON customerorder.custno = C.custno 
       INNER JOIN (SELECT orderno, SUM(actualprice) AS actualprice
                     FROM orderline 
                 GROUP BY orderno)
               ON customerorder.orderno = orderline.orderno 
GROUP  BY C.custno, 
          companyname 
于 2012-11-14T11:35:29.747 回答
1

尝试这个

SELECT C.custno, 
       companyname, 
       Count(Distinct customerorder.orderno)AS 'Total Orders', 
       Sum(orderline.actualprice) 
FROM   customer C 
       INNER JOIN customerorder 
               ON customerorder.custno = C.custno 
       INNER JOIN orderline 
               ON customerorder.orderno = orderline.orderno 
GROUP  BY C.custno, 
          companyname

对 DISTINCT 订单号使用计数

于 2012-11-14T11:33:37.737 回答