如何在单个查询中聚合不同表的值?

时间:2016-05-20 20:14:44

标签: sql join sum subquery

Tables Diagram

这些是我在3张桌子上的数据。

select*from ShippingDetails 
ProductCode   Shipping Quantity
 MFD01-10            50 
 MFD01-07            50  
 MFD01-10            10 

select*from ProductDetails
 ProductCode   Shipping Quantity
   MFD01-07          500
   MFD01-10          100
   MFD01-07         1000
   MSD01-21          200                   

  select*from StockData
  ProductCode     UrunAdi ( " Product Name")
  MFD01-07        7  mm FTube       
  MFD01-10        10 mm FTube       
  MSD01-21        21 mm STube   
  MSD01-27        27 mm STube   

我尝试编写这两个查询,但它没有用。我无法合并为一张桌子。

  select StockData.ProductCode,SUM( ProductDetails.ProductQuantity) as ' Product Quantity' from ProductDetails RIGHT OUTER JOIN StockData on ProductDetails.ProductCode=StockData.ProductCode group by StockData.ProductCode



 Product Code     Product Quantity
 MFD01-07               1500
 MFD01-10               100   
 MSD01-21               200
 MSD01-27               NULL

 select StockData.ProductCode, SUM ( ShippingDetails.ShippingQuantity) as ' Shipping Quantity' from ShippingDetails RIGHT OUTER JOIN StockData on ShippingDetails.ProductCode=StockData.ProductCode group by StockData.ProductCode
Product Code     Shipping Quantity
 MFD01-07               50
 MFD01-10               60  
 MSD01-21               NULL
 MSD01-27               NULL

我需要的结果。哪个查询可以提供?如果你解决我的问题,我将不胜感激。

 Product Code     (Product-Shipping) Quantity
 MFD01-07               1450
 MFD01-10               40  
 MSD01-21               200
 MSD01-27               NULL

1 个答案:

答案 0 :(得分:0)

每个表都需要一个子查询,然后连接在一起计算总数。

<强> SQL Fiddle Demo

SELECT SD.[ProductCode],
       COALESCE(PD.stock, 0) - COALESCE(D.sales, 0)  as [(Product-Shipping) Quantity]
FROM StockData SD    
LEFT JOIN (SELECT [ProductCode], SUM([Product Quantity]) stock
           FROM ProductDetails
           GROUP BY [ProductCode]) PD
       ON SD.[ProductCode] = PD.[ProductCode]
LEFT JOIN (SELECT [ProductCode], SUM([Shipping Quantity]) sales
           FROM ShippingDetails
           GROUP BY [ProductCode]) D
       ON SD.[ProductCode] = D.[ProductCode]

输出

| ProductCode | (Product-Shipping) Quantity |
|-------------|-----------------------------|
|    MFD01-07 |                        1450 |
|    MFD01-10 |                          40 |
|    MSD01-21 |                         200 |
|    MSD01-27 |                           0 |