2008-11-06 81 views
25

如何使用別名,比如查詢「按組」:集團通過別名(甲骨文)

select count(*), (select * from....) as alias_column 
from table 
group by alias_column 

我得到「alias_column」:INVALID_IDENTIFIER錯誤消息。爲什麼?如何分組這個查詢?

回答

54
select 
    count(count_col), 
    alias_column 
from 
    (
    select 
    count_col, 
    (select value from....) as alias_column 
    from 
    table 
) as inline 
group by 
    alias_column 

如果您在GROUP BY子句中重複各自的表達式,則通常可以進行分組。僅僅提到一個別名是不可能的,因爲SELECT步驟是發生查詢執行的最後一步,分組發生在更早的時候,別名尚未定義。

對於GROUP BY子查詢的結果,您將不得不稍微繞行並使用嵌套查詢,如上所述。

7

巢與別名欄查詢:

select count(*), alias_column 
from 
(select empno, (select deptno from emp where emp.empno = e.empno) as alias_column 
    from emp e 
) 
group by alias_column; 
1
select count(*), (select * from....) as alias_column 
from table 
group by (select * from....) 

在Oracle中,你不能在group by子句中使用別名。

2

要在Oracle中使用別名,您需要確保別名在您正在使用別名的位置由您的查詢定義。

最直接的方式做,這是簡單地把原來的查詢作爲子查詢 - 在這種情況下,

select count(*), (select * from....) as alias_column 
from table 
group by (select * from....) 

成爲

select count, alias_column 
from 
    (select count(*) as count, (select * from....) as alias_column 
    from table) 
group by alias_column 

我不能表現說話的含義,但如果你試圖在查詢中重新使用別名,它的寫法會非常快 - 將所有內容都放在括號內並跳起一級...