ORA-00904: 子查询中的无效标识符(在选择子句中)

Posted

技术标签:

【中文标题】ORA-00904: 子查询中的无效标识符(在选择子句中)【英文标题】:ORA-00904: invalid identifier in subquery (in select clause) 【发布时间】:2016-07-19 12:44:03 【问题描述】:

我有一个子查询需要使用外部查询中的值。它失败是因为臭名昭著的“Oracle 中的子查询无法从父查询中访问超过两级以上的值”的问题。

但是,我不知道如何重写它。网络上的大多数示例都是针对子查询在 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
;

【问题讨论】:

Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production 【参考方案1】:

您可以尝试使用不带子查询的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

【讨论】:

太完美了!非常感谢!

以上是关于ORA-00904: 子查询中的无效标识符(在选择子句中)的主要内容,如果未能解决你的问题,请参考以下文章

ORACLE ORA-00904: 无效标识符错误

SQL 错误:ORA-00904: : 第 4 行中的标识符无效

ORA-00904: 无效标识符 00904. 00000 - "%s: 无效标识符"

ora 00904标识符无效

模糊 ORA-00904 标识符无效错误

ORA-00904: 相关子查询上的列名无效