我已编写此查询来从两个表中获取余额

时间:2018-12-02 16:34:25

标签: sql sql-server-2008

我已经编写了此查询来从两个表中获取试用余额,但是我仅获得一个表值,另一个表值为null,

SELECT    
    GL.AccountId, Ca.Code AS Code, CA.AccountName AS AccountName,
    SUM(CASE GL.DrCr WHEN 2 THEN Amount END) AS Debit,
    SUM(CASE GL.DrCr WHEN 1 THEN Amount END) AS Credit,
    SUM(CASE o.DrOrCr WHEN 2 THEN o.Balance END) AS OpeningDebit,
    SUM(CASE o.DrOrCr WHEN 1 THEN o.Balance 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

this is the output

2 个答案:

答案 0 :(得分:0)

您需要对可为空的数字列使用ISNULL()。否则,如果存在空值,则在汇总时可能只会看到空值。

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

答案 1 :(得分:0)

对于剩下的记录,需要添加一个条件来满足OpeningBalance.AccountId中不存在的ClietnAccount ID的记录

  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 WHEN o.DrOrCr=2 THEN ISNULL(o.Balance,0) 
                    WHEN o.DrOrCr IS NULL then 0 END
               ) AS OpeningDebit,
           SUM(CASE WHEN o.DrOrCr=1 THEN ISNULL(o.Balance,0) 
                    WHEN o.DrOrCr IS NULL then 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