SQL多个JOIN查询未成功

时间:2014-03-29 06:00:02

标签: sql sql-server join

背景

我有三个表:StockPurchaseEntrySalesEntry

这些表格中包含ProductNameMRPLandinPriceQty字段。

我需要加入这些表格,以便SUM(Qty)PurchaseEntry中的SalesEntry使用相同的ProductNameMRP和{{1} } LandinPrice

问题

我尝试使用以下查询,但结果并非如我所愿。

<{1}} Stock SUM(Qty)给出了一些随机结果,而PurchaseEntry的{​​{1}}是正确的。

但当我单独使用SUM(Qty) SalesEntry时,我会得到正确的值。

问题

我如何才能获得正确的结果,以及应该使用什么类型的JOIN

SQL代码

PurchaseEntry

解决:

我尝试自己更改查询。我得到了我需要的正确输出。以下是查询。

JOIN

2 个答案:

答案 0 :(得分:1)

您可以尝试类似

的内容
SELECT Stock.ProductName,Stock.MRP,Stock.LandinPrice, 
       (SELECT SUM(PurchaseEntry.TotalQty)
          FROM PurchaseEntry
         WHERE PurchaseEntry.ProductName=Stock.ProductName
           AND PurchaseEntry.MRP=Stock.MRP
           AND PurchaseEntry.LandinPrice=Stock.LandinPrice) AS PurchaseQty
       (SELECT SUM(SalesEntry.Qty)
          FROM SalesEntry
         WHERE SalesEntry.ProductName=Stock.ProductName
           AND SalesEntry.MRPPrice=Stock.MRP
           AND SalesEntry.LandingAmt=Stock.LandinPrice) AS SalesQty
  FROM Stock

您现有的查询会将PurchaseQty乘以销售数量和SalesQty乘以购买数量。当然,我假设库存ProductName,MRP和LandinPrice的组合是唯一的。

答案 1 :(得分:0)

SELECT 
Stock.ProductName,
Stock.MRP,
Stock.LandinPrice, 
SUM(PurchaseEntry.TotalQty) AS PurchaseQty, 
Sales.SalesQty
FROM 
Stock 
INNER JOIN PurchaseEntry ON Stock.ProductName = PurchaseEntry.ProductName AND Stock.MRP = PurchaseEntry.MRP 
AND Stock.LandinPrice = PurchaseEntry.LandinPrice
INNER JOIN
(
    SELECT SUM(SE.Qty) AS 'SalesQty', SE.ProductName, SE.LandingAmt, SE.MRPPrice
    FROM SalesEntry SE INNER JOIN 
    Stock S ON S.LandinPrice = SE.LandingAmt AND S.MRP = SE.MRPPrice AND S.ProductName = SE.ProductName
    GROUP BY SE.ProductName, SE.LandingAmt, SE.MRPPrice
) Sales ON Sales.ProductName = Stock.ProductName AND Sales.LandingAmt = Stock.LandinPrice
AND Sales.MRPPrice = Stock.MRP
GROUP BY 
Stock.ProductName,
Stock.MRP,
Stock.LandinPrice