用0替换null sql

时间:2018-02-21 14:49:22

标签: sql

Select t.a,sum(s.value) e, sum(r.value) i
CASE when e is NULL then '0' else i end 
from table1 t
LEFT JOIN table2 s
ON t.name = s.in
LEFT JOIN table2 r
ON t.name = r.out
group by a
ORDER BY a

我的查询有错误状态,如42601,如何用'0'替换空值来解决这个问题?

2 个答案:

答案 0 :(得分:3)

您无法在创建的同一级别使用ALIAS。您必须使用汇总表单:

Select  t.a,
        sum(s.value) e, 
        sum(r.value) i,
        CASE when sum(s.value) is NULL then 0 else sum(r.value) end 
from table1 t 
    LEFT JOIN table2 s ON t.name = s.in 
    LEFT JOIN table2 r ON t.name = r.out 
group by a 
ORDER BY a

否则,如果您仍想使用ALIAS

,请将其包装在子查询中
SELECT  a, e, i,
        CASE when e is NULL then 0 else i end
FROM
    (
        Select  t.a,
                sum(s.value) e, 
                sum(r.value) i 
        from table1 t 
            LEFT JOIN table2 s ON t.name = s.in 
            LEFT JOIN table2 r ON t.name = r.out 
        group by a 
    ) subquery
ORDER BY a

答案 1 :(得分:0)

您可以使用ISNULL

Select t.a,sum(ISNULL(s.value,0)) e, sum(r.value) i
from table1 t
LEFT JOIN table2 s
ON t.name = s.in
LEFT JOIN table2 r
ON t.name = r.out
group by a
ORDER BY a