我已经写了这个查询来从期初余额表和gernalledger表中选择匹配和不匹配的两行,但是它只显示两个表中的匹配行,我想从openingbalance表中选择所有行,>
SELECT GL.AccountId,Ca.Code as Code,CA.AccountName as AccountName,
SUM(CASE GL.DrCr WHEN 2 THEN ISNULL(Amount,0) END) AS Debit,
SUM(CASE GL.DrCr WHEN 1 THEN ISNULL(Amount,0) END) AS Credit,
SUM(CASE o.DrOrCr WHEN 2 THEN ISNULL(o.Balance,0) END) AS OpeningDebit,
SUM(CASE o.DrOrCr WHEN 1 THEN ISNULL(o.Balance,0) END) AS OpeningCredit
FROM GeneralLedgerLine GL
Join ClientAccount CA On GL.AccountId = CA.Id
Left Join OpeningBalance o on o.AccountId=CA.Id
Where CA.ClientId = 1
GROUP BY GL.AccountId,CA.Code,CA.AccountName
答案 0 :(得分:1)
您可以对三个表使用左联接,并在On子句(而不是Where子句)中移动CA.ClientId = 1
SELECT GL.AccountId,Ca.Code as Code,CA.AccountName as AccountName,
SUM(CASE GL.DrCr WHEN 2 THEN ISNULL(Amount,0) END) AS Debit,
SUM(CASE GL.DrCr WHEN 1 THEN ISNULL(Amount,0) END) AS Credit,
SUM(CASE o.DrOrCr WHEN 2 THEN ISNULL(o.Balance,0) END) AS OpeningDebit,
SUM(CASE o.DrOrCr WHEN 1 THEN ISNULL(o.Balance,0) END) AS OpeningCredit
FROM GeneralLedgerLine GL
LEft Join ClientAccount CA On GL.AccountId = CA.Id
Left Join OpeningBalance o on o.AccountId=CA.Id
and CA.ClientId = 1
GROUP BY GL.AccountId,CA.Code,CA.AccountName
答案 1 :(得分:0)
尝试一下:
Full Outer Join OpeningBalance o on o.AccountId=CA.Id
答案 2 :(得分:0)
如果要从两个表中获取数据,请在下面的查询中使用FULL OUTER JOIN而不是LEFT JOIN,
还将o.AccountId上的OpeningBalance表与GeneralLedgerLine表中的GL.AccountId结合起来
SELECT GL.AccountId,Ca.Code as Code,CA.AccountName as AccountName,
SUM(CASE GL.DrCr WHEN 2 THEN ISNULL(Amount,0) END) AS Debit,
SUM(CASE GL.DrCr WHEN 1 THEN ISNULL(Amount,0) END) AS Credit,
SUM(CASE o.DrOrCr WHEN 2 THEN ISNULL(o.Balance,0) END) AS OpeningDebit,
SUM(CASE o.DrOrCr WHEN 1 THEN ISNULL(o.Balance,0) END) AS OpeningCredit
FROM GeneralLedgerLine GL
Join ClientAccount CA On GL.AccountId = CA.Id
FULL OUTER Join OpeningBalance o on o.AccountId=GL.AccountId
Where CA.ClientId = 1
GROUP BY GL.AccountId,CA.Code,CA.AccountName
如果要从OpeningBalance表中选择所有行,而不是从GeneralLedgerLine表中选择所有行,则在查询中使用RIGHT OUTER JOIN而不是LEFT JOIN,
还将o.AccountId上的OpeningBalance表与GeneralLedgerLine表中的GL.AccountId结合起来
SELECT GL.AccountId,Ca.Code as Code,CA.AccountName as AccountName,
SUM(CASE GL.DrCr WHEN 2 THEN ISNULL(Amount,0) END) AS Debit,
SUM(CASE GL.DrCr WHEN 1 THEN ISNULL(Amount,0) END) AS Credit,
SUM(CASE o.DrOrCr WHEN 2 THEN ISNULL(o.Balance,0) END) AS OpeningDebit,
SUM(CASE o.DrOrCr WHEN 1 THEN ISNULL(o.Balance,0) END) AS OpeningCredit
FROM GeneralLedgerLine GL
Join ClientAccount CA On GL.AccountId = CA.Id
RIGHT OUTER Join OpeningBalance o on o.AccountId=GL.AccountId
Where CA.ClientId = 1
GROUP BY GL.AccountId,CA.Code,CA.AccountName