在子查询中使用“左联接”检索所有行

时间:2018-09-09 19:21:09

标签: sql sql-server-2008-r2 subquery

使用SQL Server 2008 R2,我在使用具有两个不同日期范围的子查询中的左联接检索行时遇到问题。

Tables that i used to store values

到目前为止,我使用此sql来检索输出(从堆栈溢出中学习)

SELECT 
    TT.TransferRId, RM.ResourceName AS BookName, 
    COALESCE(Opening,0) AS Opening, 
    SUM(TT.InwardQty) AS Inward, 
    SUM(TT.OutwardQty) AS Outward, 
    COALESCE((Opening + (SUM(TT.InwardQty)) - (SUM(TT.OutwardQty))), 0) AS Closing
FROM 
    ((ResourceMaster RM 
LEFT JOIN 
    TransferTrans TT ON TT.TransferRId = RM.ResourceId)
LEFT JOIN 
    TransferRegister TR ON TR.TransferRegisterId = TT.TransRegisterId)
LEFT JOIN 
    (SELECT 
         TT.TransferRId,
         (SUM(TT.InwardQty)- SUM(TT.OutwardQty)) AS Opening
     FROM 
         TransferTrans TT  
     LEFT JOIN 
         TransferRegister TR ON TR.TransferRegisterId = TT.TransRegisterId
     WHERE 
         TR.TransferDate < '2018-09-01'
         AND TT.Siteid = 2 
     GROUP BY 
         TT.TransferRId) AS Stock ON Stock.TransferRId = TT.TransferRId
WHERE 
    TT.Siteid = 2
    AND TR.TransferDate BETWEEN '2018-09-01' AND '2018-09-30'
GROUP BY 
    TT.TransferRId, RM.ResourceName, Opening

Output for Above Query

Expected Output

进一步建议获得预期的输出。提前致谢。

1 个答案:

答案 0 :(得分:1)

TransferDate上的where条件将“左连接”更改为“内部连接”,然后将其移到“打开”上:

SELECT 
    TT.TransferRId, RM.ResourceName AS BookName, 
    COALESCE(Opening,0) AS Opening, 
    SUM(TT.InwardQty) AS Inward, 
    SUM(TT.OutwardQty) AS Outward, 
    COALESCE((Opening + (SUM(TT.InwardQty)) - (SUM(TT.OutwardQty))), 0) AS Closing
FROM 
    ResourceMaster RM 
LEFT JOIN 
    TransferTrans TT ON TT.TransferRId = RM.ResourceId
LEFT JOIN 
    TransferRegister TR
  ON TR.TransferRegisterId = TT.TransRegisterId
 AND TR.TransferDate BETWEEN '2018-09-01' AND '2018-09-30'
LEFT JOIN 
    (SELECT 
         TT.TransferRId,
         (SUM(TT.InwardQty)- SUM(TT.OutwardQty)) AS Opening
     FROM 
         TransferTrans TT  
     LEFT JOIN 
         TransferRegister TR 
       ON TR.TransferRegisterId = TT.TransRegisterId
      AND TR.TransferDate < '2018-09-01'
     WHERE TT.Siteid = 2 
     GROUP BY 
         TT.TransferRId) AS Stock ON Stock.TransferRId = TT.TransferRId
WHERE 
    TT.Siteid = 2
GROUP BY 
    TT.TransferRId, RM.ResourceName, Opening

通常有一条经验法则:外表的条件放在WHERE中,而内表的条件AND放在ON中的联接条件< / p>