SQL多重联接查询不成功
背景 我有三个表:SQL多重联接查询不成功,sql,sql-server,join,Sql,Sql Server,Join,背景 我有三个表:Stock,PurchaseEntry,和saleentry 这些表格共有字段ProductName、MRP、LandinPrice和Qty 我需要加入这些表,以便在PurchaseEntry和SalesEntry中使用与ProductName、MRP和LandinPrice相同的Stock获取SUM(数量) 问题 我尝试使用以下查询,但结果不是我想要的 PurchaseEntry的SUM(Qty)给出了一些随机结果,而saleEntry的SUM(Qty)是正确的 但是当我单独
Stock
,PurchaseEntry
,和saleentry
这些表格共有字段ProductName
、MRP
、LandinPrice
和Qty
我需要加入这些表,以便在PurchaseEntry
和SalesEntry
中使用与ProductName
、MRP
和LandinPrice
相同的Stock
获取SUM(数量)
问题
我尝试使用以下查询,但结果不是我想要的
PurchaseEntry的SUM(Qty)
给出了一些随机结果,而saleEntry的SUM(Qty)
是正确的
但是当我单独在PurchaseEntry
上使用JOIN
时,我得到了正确的值
问题
如何获得正确的结果,以及应使用何种类型的JOIN
s
SQL代码
SELECT Stock.ProductName,
Stock.MRP,
Stock.LandinPrice,
SUM(PurchaseEntry.TotalQty)
AS PurchaseQty,
SUM(SalesEntry.Qty)
AS SalesQty
FROM Stock
JOIN PurchaseEntry
ON Stock.ProductName = PurchaseEntry.ProductName
AND Stock.MRP = PurchaseEntry.MRP
AND Stock.LandinPrice = PurchaseEntry.LandinPrice
JOIN SalesEntry
ON Stock.ProductName = SalesEntry.ProductName
AND Stock.MRP = SalesEntry.MRPPrice
AND Stock.LandinPrice = SalesEntry.LandingAmt
GROUP BY Stock.ProductName,
Stock.MRP,
Stock.LandinPrice
已解决:
我试着自己改变这个问题。我得到了我所需要的正确输出。下面是这个问题
SELECT Stock.ProductName,
Stock.MRP,Stock.LandinPrice,
(SELECT SUM(PurchaseEntry.TotalQty)
FROM PurchaseEntry
WHERE Stock.ProductName=PurchaseEntry.ProductName
AND Stock.MRP=PurchaseEntry.MRP
AND Stock.LandinPrice=PurchaseEntry.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
GROUP BY Stock.ProductName,Stock.MRP,Stock.LandinPrice
你可以试试类似的东西
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乘以购买数量。当然,我假设stock ProductName、MRP和LandinPrice的组合是唯一的。很抱歉,这也产生了相同的结果。这产生了一个错误-列“Sales.saleqty”在选择列表中无效,因为它既不包含在聚合函数中,也不包含在GROUP BY子句中。我自己发现了这个问题,并编辑了这个问题,请查收。无论如何,这也在执行时出现了一个错误。关键字“ON”附近的语法不正确。如果您自己找到了解决方案,但下面的答案都不正确,请将该解决方案粘贴为新答案并将其标记为已回答。抱歉,我无法执行此操作。它说你必须等8个小时才能自己发布答案。也许是因为我在这里。
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