在Oracle中引用别名子查询

时间:2018-10-25 11:28:32

标签: sql oracle

我有以下查询:

select
        A.A_ID,
        B.Lib,
        A.Lib,
        C.Lib,
        (SELECT count(*) FROM X WHERE A.A_ID = X.A_ID) AS countX,
        (SELECT count(*) FROM Y WHERE A.A_ID = Y.A_ID) AS countY,
        (SELECT count(*) FROM Z WHERE A.A_ID = Z.A_ID) AS countZ
    from
        A
    left outer join
        C
            on A.C_ID=C.C_ID
    left outer join
        B
            on A.B_ID=B.B_ID
    WHERE
        countX = 2 AND countY = 3
    ORDER BY 
        countZ DESC;

但这给了我以下错误:

  

SQL错误[904] [42000]:ORA-00904:“ COL_5_0_”:未识别   有效期

我该如何解决?

1 个答案:

答案 0 :(得分:1)

尝试如下,我认为您错过的类型分组将是排序

with cte as
(

select
        A.A_ID,
        B.Lib,
        A.Lib,
        C.Lib,
        (SELECT count(*) FROM X WHERE A.A_ID = X.A_ID) AS countX,
        (SELECT count(*) FROM Y WHERE A.A_ID = Y.A_ID) AS countY,
        (SELECT count(*) FROM Z WHERE A.A_ID = Z.A_ID) AS countZ
    from
        A
    left outer join
        C
            on A.C_ID=C.C_ID
    left outer join
        B
            on A.B_ID=B.B_ID
) select * from cte where countX = 2 AND countY = 3
    Order BY 
    countZ DESC