Sql表左外连接结果Group By

时间:2016-10-08 20:02:55

标签: sql sql-server tsql

产品1

3张发票的购买数量为50 + 100 + 50 = 200和

1张发票的销售数量为10

我使用下面的代码将结果作为

Total Purchase - Total Sale = Closing Qty 
     200       -      10    = 290

但是我得到了错误的结果,如附图所示:

enter image description here

请指导我更正我的代码

SELECT 
    P.PRODUCT as PRODUCTNAME,
    P.QUANTITY AS PURCHASE,
    ISNULL(S.QUANTITY, 0) AS SALE,
    ISNULL(P.QUANTITY, 0) - ISNULL(s.QUANTITY, 0) AS CLOSINGQTY
FROM 
    [PurchaseData] P 
LEFT OUTER JOIN 
    [DeliveryData1] S ON P.Product = s.PRODUCT

3 个答案:

答案 0 :(得分:0)

如果您想要最终结果,则应使用sum和group by

      SELECT 
        P.PRODUCT as PRODUCTNAME,
        sum(P.QUANTITY AS PURCHASE),
        sum(isnull(S.QUANTITY,0)) AS SALE,
        sum(isnull(P.QUANTITY,0))-sum(isnull(s.QUANTITY,0)) AS CLOSINGQTY

    FROM [PurchaseData] P LEFT OUTER JOIN [DeliveryData1] S ON P.Product = s.PRODUCT
    GROUP BY P.PRODUCT

答案 1 :(得分:0)

如果我理解正确,您就会遇到问题,因为您有给定产品的多个购买记录。如果是这种情况,那么只需在 JOIN之前汇总

SELECT p.*, COALESCE(S.QUANTITY, 0) AS SALE,
       COALESCE(P.QUANTITY, 0)-COALESCE(s.QUANTITY, 0) AS CLOSINGQTY
FROM (SELECT p.product, p.quantity
      FROM PurchaseData P
      GROUP BY p.product
     ) p LEFT OUTER JOIN 
     DeliveryData1 S
     ON P.product = s.producct;

实际上,我不清楚这两个表中哪一个有重复 - 或者两者都有。因此,您可能需要为S执行类似操作。

答案 2 :(得分:0)

使用来自不同表的聚合时,不要加入表并聚合,然后先聚合并加入聚合:

select
  p.product as productname,
  p.sum_quantity as purchase,
  coalesce(s.sum_quantity, 0) as sale,
  p.sum_quantity - coalesce(s.sum_quantity, 0) as closingqty
from
(
  select product, sum(quantity) as sum_quantity
  from purchasedata
  group by product
) p
left join
(
  select product, sum(quantity) as sum_quantity
  from deliverydata1
  group by product  
) s on s.product = p.product;

我已将ifnull替换为coalesce,因此该查询完全符合标准SQL。