使用Sub Query中的Left Join检索所有行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Sub Query中的Left Join检索所有行相关的知识,希望对你有一定的参考价值。

使用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

建议进一步获得预期的产量。提前致谢。

答案

TransferDate上的Where-condition将Left连接更改为Inner Join,将其移动到On:

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中,而内表上的条件是ANDed到ON中的连接条件

以上是关于使用Sub Query中的Left Join检索所有行的主要内容,如果未能解决你的问题,请参考以下文章

使用 LEFT JOIN 时的 ISNULL() 与 ISNULL 性能

在 MySQL 和 PHP 中使用多表和 LEFT JOIN 查询非常慢

LEFT JOIN,如果存在第二个表的结果,则添加到 PHP 中的数组

Spring Data 'Left Join Fetch' 查询返回 null

SQL LEFT JOIN与IN使用案例说明

SQL LEFT JOIN与IN使用案例说明