如何在SQL Server中使用0而不是NULL

时间:2014-09-02 23:55:42

标签: sql sql-server null coalesce

查看以下查询:

WITH TEMP([Company], [Company Name], [GL Description], [Amount], [BeginBal])
AS
(
    SELECT 
       GLAC.GLCo AS Company, 
       HQCO.Name AS 'Company Name', 
       GLAC.Description AS 'GL Description', 
       SUM(GLDT.Amount) AS Amount, 
       GLYB.BeginBal 
    FROM 
       GLAC 
    LEFT JOIN 
       HQCO ON GLAC.GLCo = HQCO.HQCo
    LEFT JOIN 
       GLDT ON GLAC.GLCo = GLDT.GLCo AND GLAC.GLAcct = GLDT.GLAcct
    LEFT JOIN 
       GLYB ON GLAC.GLCo = GLYB.GLCo AND GLAC.GLAcct = GLYB.GLAcct
    WHERE 
       GLAC.udCategory = 'Cash At Bank' 
       AND GLAC.Active = 'Y'  
       AND (GLAC.GLCo = 1 or GLAC.GLCo = 5 or GLAC.GLCo = 6 or GLAC.GLCo = 7) 
       AND GLYB.FYEMO = '2012-06-01 00:00:00' 
    GROUP BY
       GLAC.GLCo, HQCO.Name , GLAC.Description, GLYB.BeginBal
)
SELECT
    Company, [Company Name], [GL Description], Amount + BeginBal as 'Balance' 
FROM 
    TEMP

这产生了下表:

 +---------+----------------------+------------------------------+-------------+
| Company |     Company Name     |        GL Description        |   Balance   |
+---------+----------------------+------------------------------+-------------+
|       1 | Contracting Pty Ltd  | Cash At Bank ANZ Cheque a/c  | -8423347.81 |
|       1 |  Contracting Pty Ltd | Investment Online Saver Acct | 15040000    |
|       1 |  Contracting Pty Ltd | Westpac Bonus Cash Reserve   | 123133      |
|       5 | ABC UTC PTY LTD      | Cash At Bank ANZ Cheque a/c  | 13121902.53 |
|       6 | ABC UTC PTY LTD      | Cash At Bank ANZ Cheque a/c  | 3932872.45  |
|       6 | ABC UTC PTY LTD      | Investment Online Saver Acct | 142448      |
|       7 |  Plant Hire Pty Ltd  | Cash At Bank ANZ Cheque a/c  | 253253.32   |
+---------+----------------------+------------------------------+-------------+

我的一些数据丢失了,这是因为这一行:

GLYB.FYEMO = '2012-06-01 00:00:00' 

问题是'GLAC'中的某些记录在GLYB中没有值,因此null值不会出现在我的表中。

如果符合以下任何条件,我怎样才能显示所有记录:

  • GLYB.FYEMO = '2012-06-01 00:00:00'
  • GLYB.FYEMO is null

1 个答案:

答案 0 :(得分:1)

我认为你需要将条件移到on子句,因为where将外连接转换为内连接:

WITH TEMP([Company], [Company Name], [GL Description], [Amount], [BeginBal]) AS (
      select GLAC.GLCo as Company, HQCO.Name as [Company Name], GLAC.Description as [GL Description], 
             SUM(GLDT.Amount) as Amount, GLYB.BeginBal
      from GLAC LEFT JOIN
           HQCO
           ON GLAC.GLCo = HQCO.HQCo LEFT JOIN
           GLDT
           ON GLAC.GLCo = GLDT.GLCo and GLAC.GLAcct = GLDT.GLAcct LEFT JOIN
           GLYB
           ON GLAC.GLCo = GLYB.GLCo and
              GLAC.GLAcct = GLYB.GLAcct and
              GLYB.FYEMO = '2012-06-01 00:00:00' 
      where GLAC.udCategory = 'Cash At Bank' and GLAC.Active = 'Y'  and
            (GLAC.GLCo in (1, 5, 6, 7)
      Group By GLAC.GLCo, HQCO.Name , GLAC.Description, GLYB.BeginBal
     )
Select Company, [Company Name], [GL Description], Amount + BeginBal as Balance
from TEMP;