我有一个需要使用外部查询中的值的子查询。它失败是因为臭名昭着的“Oracle中的子查询无法从父查询中访问超过两级更深层次的问题”。
然而,我无法弄清楚如何重写它。 Web上的大多数示例都适用于子查询在WHERE子句中的情况;我的是SELECT条款。
帮助任何人?
select agre.*, agre.orga_ky,
orga.NAME_LA_LB as orga_name,
pers.LAST_NAME_LA_LB as SIGNATORY_ORGA__LASTNAME, pers.FIRST_NAME_LA_LB as SIGNATORY_ORGA_FIRSTNAME,
upper(pers.LAST_NAME_LA_LB) || ' ' || pers.FIRST_NAME_LA_LB as SIGNATORY_ORGA_FULLNAME,
-- Get the most current agreement for this orga and compare it with this row to find out if this row is current or expired
CASE WHEN (
SELECT AGRE_KY
FROM (
SELECT a.AGRE_KY
FROM T_AGREEMENT a
WHERE a.ORGA_KY = agre.orga_ky -- fail!!! ORA-00904: invalid identifier
ORDER BY a.REC_CREATION_DT DESC
)
WHERE ROWNUM = 1
) = agre.agre_ky THEN 'Current' ELSE 'Expired' END as agreement_status
from T_AGREEMENT agre
left outer join T_ORGANIZATION orga on agre.orga_ky = orga.orga_ky
left outer join T_PERSON pers on agre.SIGNATORY_ORGA_PERS_KY = pers.pers_ky
;
答案 0 :(得分:2)
您可以尝试使用row_number
窗口函数而不使用子查询,并检查它是否返回预期结果。
select agre.*, agre.orga_ky,
orga.NAME_LA_LB as orga_name,
pers.LAST_NAME_LA_LB as SIGNATORY_ORGA__LASTNAME, pers.FIRST_NAME_LA_LB as SIGNATORY_ORGA_FIRSTNAME,
upper(pers.LAST_NAME_LA_LB) || ' ' || pers.FIRST_NAME_LA_LB as SIGNATORY_ORGA_FULLNAME,
-- Get the most current agreement for this orga and compare it with this row to find out if this row is current or expired
CASE WHEN row_number() over(partition by agre.orga_ky order by agre.REC_CREATION_DT desc)
----------------^^^^^^^^^^^^ change the partitioning column per your requirement
= 1 THEN 'CURRENT'
ELSE 'EXPIRED' END as agreement_status
from T_AGREEMENT agre
left outer join T_ORGANIZATION orga on agre.orga_ky = orga.orga_ky
left outer join T_PERSON pers on agre.SIGNATORY_ORGA_PERS_KY = pers.pers_ky