SUM干扰COUNT

时间:2012-11-14 11:30:23

标签: sql sql-server-2008-r2

使用此查询,我得到每个客户放置了多少订单的结果。但是,当我在SELECT字段中使用SUM(OrderLine.ActualPrice)并使用内部联接将Order表链接到包含价格的OrderLine表时。 COUNT结果是倾斜的,因为OrderLine表包含同一订单的多个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个结果。

2 个答案:

答案 0 :(得分: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:多

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 

答案 1 :(得分: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订单号上使用Count