如果SQL中的列为空,则返回空白数据

时间:2016-01-07 15:20:41

标签: sql

我运行了以下查询,该查询返回36行数据

SELECT 
    A.OBJECTIVE, SUM(A.T_VALUE)
FROM 
    DB2ADM2.TFINTR10 A
WHERE 
    (A."YEAR" =10)
    AND (A.OBJECTIVE BETWEEN 'WAAAA' AND 'WZZZZ')
GROUP BY 
    A.OBJECTIVE


When I merge with another table and add the Narration field (OB_Narr5) the rows of data are reduced as the Ob_Narr5 does not exist for every Objective, see sql.

    SELECT A.OBJECTIVE, SUM ( A.T_VALUE ), B.OB_NARR5
    FROM DB2ADM2.TFINTR10 A INNER JOIN DB2ADM2.TFINOBJP B ON B.OB_12345 = A.
         OBJECTIVE
    WHERE (A."YEAR" =10)
    AND A.OBJECTIVE BETWEEN 'WAAAA' AND 'WZZZZ'
    GROUP BY A.OBJECTIVE, B.OB_NARR5

The rows returned are now only 4.

How can I return all the rows including the blank fields and / or return just the rows with the blank fields?

感谢回复,Left和Full Outer Join都有效。

How do I replace the <NULL> with a blank instead please?

WAAAA   -173597.12  <NULL>
WABAA   222717.76   GENERAL                         

3 个答案:

答案 0 :(得分:5)

使用LEFT JOIN而非INNER JOIN不会删除包含空列的左表的条目

答案 1 :(得分:0)

select A.OBJECTIVE
    ,SUM(A.T_VALUE)
    ,B.OB_NARR5
from DB2ADM2.TFINTR10 A
left join DB2ADM2.TFINOBJP B on B.OB_12345 = A.OBJECTIVE
where A."YEAR" = 10
    and A.OBJECTIVE between 'WAAAA' and 'WZZZZ'
group by A.OBJECTIVE
    ,B.OB_NARR5

答案 2 :(得分:0)

您可以使用完全外部联接来保留两个表中的值 或任何特定表的左外连接