无法从其他已加入的表

时间:2017-06-21 03:31:33

标签: sql oracle left-join

我有一些包含大量数据的表,因此我尝试使用该数据创建一种报告,基于使用“LEFT JOIN”的某些条件,

SELECT SUBSIDIARY, MAIN_ACCOUNT, AMOUNT ... FROM (
...
LEFT JOIN (SELECT MAIN_ACCOUNT, ACCOUNT_NO AS SUBSIDIARY FROM TABLE1 WHERE STATUS = 'A') K
ON MAIN_ACCOUNT = K.MAIN_ACCOUNT
LEFT JOIN (SELECT SUM(AMOUNT) AS AMOUNT, ACCOUNT_NO, FROM TABLE2 WHERE ACCOUNT_NO = K.ACCOUNT_NO GROUP_BY ACCOUNT_NO) L
ON SUBSIDIARY = L.ACCOUNT_NO --this is where i got into a problem
...
);

问题在于,由于我在主K.ACCOUNT_NO中选择,因此我无法使用WHERE ACCOUNT_NO = SUBSIDIARY尝试过的其他联接中的SELECT。这是否意味着我无法从另一个联接访问以前查询过的数据?

我得到错误:

ORA-00904: "SUBSIDIARY": invalid identifier

如果我使用k.subsidiaryk.account_no

ORA-00904: "k.SUBSIDIARY": invalid identifier
ORA-00904: "k.account_no": invalid identifier

1 个答案:

答案 0 :(得分:1)

您无法访问K.ACCOUNT_NO,但可以使用INNER JOIN访问TABLE1

WHERE ACCOUNT_NO = K.ACCOUNT_NO

被替换

INNER JOIN TABLE1 ON TABLE2.ACCOUNT_NO = TABLE1.ACCOUNT_NO AND TABLE1.STATUS = 'A' 

我希望它有所帮助。

SELECT SUBSIDIARY, MAIN_ACCOUNT, AMOUNT ... FROM (
    ...
    LEFT JOIN (SELECT MAIN_ACCOUNT, ACCOUNT_NO AS SUBSIDIARY FROM TABLE1 WHERE STATUS = 'A') K
    ON MAIN_ACCOUNT = K.MAIN_ACCOUNT
    --this is where i got into a problem
    LEFT JOIN (SELECT SUM(AMOUNT) AS AMOUNT, ACCOUNT_NO, FROM TABLE2 INNER JOIN TABLE1 ON TABLE2.ACCOUNT_NO = TABLE1.ACCOUNT_NO AND TABLE1.STATUS = 'A' GROUP BY ACCOUNT_NO) L
    ON SUBSIDIARY = L.ACCOUNT_NO
    ...
    );