从查询返回空行

时间:2014-01-21 15:19:20

标签: sql db2

我想知道是否有人可以帮我处理我正在进行的DB2查询?

我基本上试图在DB2Cust上的两个表NOTIFICATION_REQUEControl Number之间进行左外连接。

我想返回DB2Cust中的所有行,但是,在NOTIFICATION_REQUE中,我想选择最大Notice_DT并仅返回该记录。

以下查询是我目前所拥有的。

它已关闭,但它不会返回DB2CustNOTIFICATION_REQUE中不存在的SELECT C.CONTROL_NO, NR.CONTROL_NBR, COALESCE(C.LNAME,'') AS LNAME, COALESCE(C.FNAME,'') AS FNAME, COALESCE(CAST(NR.NOTICE_DT AS VARCHAR(10)), '') AS NOTICE_DT FROM WITC00DS.DB2CUST C LEFT OUTER JOIN WITC00DS.NOTIFICATION_REQUE NR ON C.CONTROL_NO = NR.CONTROL_NBR AND C.AGENT_CODE = 'HR' AND C.STW_DATE BETWEEN '01/01/2000' AND '01/17/2014' WHERE NR.NOTICE_DT = (SELECT MAX(NOTICE_DT) FROM WITC00DS.NOTIFICATION_REQUE ZZ WHERE ZZ.CONTROL_NBR = C.CONTROL_NO) 中的控件号。

{{1}}

1 个答案:

答案 0 :(得分:0)

这是两个选择。您可以将子查询移动到on子句:

SELECT C.CONTROL_NO, NR.CONTROL_NBR, COALESCE(C.LNAME,'') AS LNAME, COALESCE(C.FNAME,'') AS FNAME,
       COALESCE(CAST(NR.NOTICE_DT AS VARCHAR(10)), '') AS NOTICE_DT 
FROM WITC00DS.DB2CUST C LEFT OUTER JOIN
     WITC00DS.NOTIFICATION_REQUE NR 
     ON C.CONTROL_NO = NR.CONTROL_NBR AND
        C.AGENT_CODE = 'HR' AND
        C.STW_DATE BETWEEN '01/01/2000' AND '01/17/2014'  AND
        NR.NOTICE_DT = (SELECT MAX(NOTICE_DT) 
                        FROM WITC00DS.NOTIFICATION_REQUE ZZ 
                        WHERE ZZ.CONTROL_NBR = C.CONTROL_NO
                       )

或者您可以在`WHERE子句:

中显式检查NULL
SELECT C.CONTROL_NO, NR.CONTROL_NBR, COALESCE(C.LNAME,'') AS LNAME, COALESCE(C.FNAME,'') AS FNAME,
       COALESCE(CAST(NR.NOTICE_DT AS VARCHAR(10)), '') AS NOTICE_DT 
FROM WITC00DS.DB2CUST C LEFT OUTER JOIN
     WITC00DS.NOTIFICATION_REQUE NR 
     ON C.CONTROL_NO = NR.CONTROL_NBR AND
        C.AGENT_CODE = 'HR' AND
        C.STW_DATE BETWEEN '01/01/2000' AND '01/17/2014'  AND
WHERE NR.NOTICE_DT is null or
      NR.NOTICE_DT = (SELECT MAX(NOTICE_DT) 
                      FROM WITC00DS.NOTIFICATION_REQUE ZZ 
                      WHERE ZZ.CONTROL_NBR = C.CONTROL_NO
                     );