将null转换为0

时间:2018-11-05 04:21:20

标签: sql null

我有脚本:

SELECT 
    dtypcode,
    debtornum AS 'Debtor Number',
    debtorchk AS 'Check Digit',
    balancedr AS 'Debit Balance',
    balancecr AS 'Credit Balance' ,
    balancedr + balancecr AS 'Balance'
FROM 
    [pthdbo].[ldrdtyp] A
JOIN 
    [pthdbo].[ldrdbtr] B ON A.tpkldrdtyp = B.tfkldrdtyp
WHERE 
    ((balancedr + balancecr) > '0'
      OR (balancedr + balancecr) < '0')
    --debtornum = '921835'
    AND dtypcode = 'OODEB'

它返回以下内容:

    OODEB       921846  1   550.00  -380.00 170.00
    OODEB       922009  5   715.00  -725.00 -10.00

但是,如果我们仅查看债务人号码“ 921835”,则会看到以下内容:

   OODEB        921835  4   200.00  NULL    NULL

由于债务人编号'921835'的贷方余额为NULL而不是0,因此该计算不起作用,并且没有在查询结果中显示为余额。

我们不想更新表格以将其可能为NULL的地方反映为0-任何人都可以阐明在“借方余额”或“贷方余额”字段中转换“ NULL”值的解决方案的解决方案飞”,这样,如果表中有贷方余额或借方余额以及其他列的NULL,则余额将被反映出来。

预先感谢

JR

4 个答案:

答案 0 :(得分:1)

您可以使用COALESCE即时处理NULL

COALESCE(balancedr,0)

在SQL Server中,您可以使用ISNULL()

ISNULL(balancedr,0)

答案 1 :(得分:1)

您可以使用ISNULL方法

ISNULL(Parameter,0)

SELECT 
 dtypcode,
 debtornum AS 'Debtor Number',
 debtorchk AS 'Check Digit',
 ISNULL(balancedr,0) AS 'Debit Balance',
 ISNULL(balancecr,0) AS 'Credit Balance' ,
 ISNULL(balancedr + balancecr) AS 'Balance'
 FROM [pthdbo].[ldrdtyp] A
 JOIN [pthdbo].[ldrdbtr] B
 ON A.tpkldrdtyp = B.tfkldrdtyp
 WHERE ((balancedr + balancecr) > '0'
 OR (balancedr + balancecr) < '0')
 --debtornum = '921835'
 AND dtypcode = 'OODEB'

答案 2 :(得分:1)

尝试一下:

SELECT 
 dtypcode,
 debtornum    AS 'Debtor Number',
 debtorchk    AS 'Check Digit',
 balancedr    AS 'Debit Balance',
 balancecr    AS 'Credit Balance' ,
 balancedr + balancecr AS 'Balance'
 FROM [pthdbo].[ldrdtyp] A
 JOIN [pthdbo].[ldrdbtr] B
 ON A.tpkldrdtyp = B.tfkldrdtyp
 WHERE ((ISNULL(balancedr,0) + ISNULL(balancecr,0)) > '0'
 OR (ISNULL(balancedr,0) + ISNULL(balancecr,0)) < '0')
 --debtornum = '921835'
 AND dtypcode = 'OODEB'

答案 3 :(得分:0)

您可以尝试使用coalesce()函数

SELECT 
   dtypcode,
   debtornum    AS 'Debtor Number',
   debtorchk    AS 'Check Digit',
   coalesce(balancedr,0)    AS 'Debit Balance',
   coalesce(balancecr,0)    AS 'Credit Balance' ,
   coalesce(balancedr,0) + coalesce(balancecr,0) AS 'Balance'
   FROM [pthdbo].[ldrdtyp] A
   JOIN [pthdbo].[ldrdbtr] B
   ON A.tpkldrdtyp = B.tfkldrdtyp
   WHERE ((coalesce(balancedr,0) + coalesce(balancecr,0)) > '0'
   OR (coalesce(balancedr,0) + coalesce(balancecr,0)) < '0')
   --debtornum = '921835'
   AND dtypcode = 'OODEB'