我想知道是否有人可以帮我处理我正在进行的DB2查询?
我基本上试图在DB2Cust
上的两个表NOTIFICATION_REQUE
和Control Number
之间进行左外连接。
我想返回DB2Cust
中的所有行,但是,在NOTIFICATION_REQUE
中,我想选择最大Notice_DT
并仅返回该记录。
以下查询是我目前所拥有的。
它已关闭,但它不会返回DB2Cust
中NOTIFICATION_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}}
答案 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
);