我正在写一个包含几个子查询的选择(下面的代码片段中只有一个),但是我很难返回仅在AIRFI_TCD子查询中有1个现有行的行。我只希望在TSUMM和TPPPRFL表上有匹配的CLT_ID时显示行。我尝试了HAVING COUNT子句(请参见下文),但这没有用。我正在空缺如何将TSUMM与子查询一起使用。
SELECT RIGHT(DIGITS (A.CLT_ID),9) || A.PGM_ID ||
RIGHT(DIGITS (A.PGM_ACCT_SQNBR),4) AS BN
, ( SELECT B.XREF_NBR
FROM GHMTUO#1.TPPPRFL B
WHERE B.PARTIC_PRFL_TCD = '04' --AIRFI
AND B.CLT_ID = A.CLT_ID
AND B.BUS_PGM_ID = A.PGM_ID
AND B.CLT_ID_TCD = '01'
AND B.PARTIC_PRFL_EDT = (SELECT MAX(X.PARTIC_PRFL_EDT)
FROM GHMTUO#1.TPPPRFL X
WHERE X.CLT_ID = B.CLT_ID)
AND B.PARTIC_PRFL_CDTTM = (SELECT MAX(Z.PARTIC_PRFL_CDTTM)
FROM GHMTUO#1.TPPPRFL Z
WHERE Z.CLT_ID = B.CLT_ID)
) AS AIRFI_TCD
FROM RAMTUO#1.TSUMM A
WHERE A.PGM_ID = 'RT'
GROUP BY A.CLT_ID, A.PGM_ID, A.PGM_ACCT_SQNBR
HAVING COUNT(AIRFI_TCD) > 1
WITH UR;
谢谢!
答案 0 :(得分:0)
这是内部联接解决方案吗?
SELECT RIGHT(DIGITS (A.CLT_ID),9) || A.PGM_ID ||
RIGHT(DIGITS (A.PGM_ACCT_SQNBR),4) AS BN,
B.XREF_NBR AS AIRFI_TCD
FROM RAMTUO#1.TSUMM A INNER JOIN GHMTUO#1.TPPPRFL B ON B.CLT_ID = A.CLT_ID AND B.BUS_PGM_ID = A.PGM_ID
WHERE A.PGM_ID = 'RT' AND B.PARTIC_PRFL_TCD = '04'
AND ...
GROUP BY A.CLT_ID, A.PGM_ID, A.PGM_ACCT_SQNBR
仅当存在匹配的CLT_ID和匹配的PGM_ID时才会显示行
答案 1 :(得分:0)
如果您只需要存在,请尝试以下操作:
SELECT RIGHT(DIGITS (A.CLT_ID),9) || A.PGM_ID ||
RIGHT(DIGITS (A.PGM_ACCT_SQNBR),4) AS BN
FROM RAMTUO#1.TSUMM A
WHERE A.PGM_ID = 'RT'
AND EXISTS
(
SELECT 1
FROM GHMTUO#1.TPPPRFL B
JOIN
(
SELECT CL
T_ID
, MAX(PARTIC_PRFL_EDT) PARTIC_PRFL_EDT
, MAX(PARTIC_PRFL_CDTTM) PARTIC_PRFL_CDTTM
FROM GHMTUO#1.TPPPRFL
GROUP BY CLT_ID
) X ON X.CLT_ID = B.CLT_ID
AND X.PARTIC_PRFL_EDT = B.PARTIC_PRFL_EDT
AND X.PARTIC_PRFL_CDTTM = B.PARTIC_PRFL_CDTTM
WHERE B.PARTIC_PRFL_TCD = '04' --AIRFI
AND B.CLT_ID = A.CLT_ID
AND B.BUS_PGM_ID = A.PGM_ID
AND B.CLT_ID_TCD = '01'
)
;
答案 2 :(得分:0)
我特别喜欢DB2的一件事是能够通过JOIN TABLE(...)将复杂的表达式甚至子查询移到新的虚拟数据字段中,如下所示:
SELECT RIGHT(DIGITS (A.CLT_ID),9) || A.PGM_ID ||
RIGHT(DIGITS (A.PGM_ACCT_SQNBR),4) AS BN
, subq.AIRFI_TCD
FROM RAMTUO#1.TSUMM A
INNER JOIN TABLE
( SELECT B.XREF_NBR,
COUNT(*)OVER() AS total_amount --number of matching entries
FROM GHMTUO#1.TPPPRFL B
WHERE B.PARTIC_PRFL_TCD = '04' --AIRFI
AND B.CLT_ID = A.CLT_ID
AND B.BUS_PGM_ID = A.PGM_ID
AND B.CLT_ID_TCD = '01'
AND B.PARTIC_PRFL_EDT = (SELECT MAX(X.PARTIC_PRFL_EDT)
FROM GHMTUO#1.TPPPRFL X
WHERE X.CLT_ID = B.CLT_ID)
AND B.PARTIC_PRFL_CDTTM = (SELECT MAX(Z.PARTIC_PRFL_CDTTM)
FROM GHMTUO#1.TPPPRFL Z
WHERE Z.CLT_ID = B.CLT_ID)
) AS subq (AIRFI_TCD, total_amount) ON subq.total_amount = 1 --instead of HAVING
WHERE A.PGM_ID = 'RT'
WITH UR;
尝试一下,希望它能起作用。