2016-07-19 88 views
2

外部問合せの値を使用する必要がある副問合せがあります。それは悪名高い "Oracleのサブクエリは、2つ以上のレベルの深い"親のクエリからの値にアクセスできないために失敗します。ORA-00904:サブクエリの無効な識別子(選択句内)

しかし、私はそれを書き直す方法を理解できません。 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

Oracle Database 11g Enterprise Editionリリース11.2.0.1.0 - 64bit Production – Junglefish

答えて

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 
+0

これは完璧です!本当にありがとう! – Junglefish