Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by alias (Oracle)

Tags:

sql

oracle

How to 'group by' a query using an alias, for example:

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

I get 'alias_column' : INVALID_IDENTIFIER error message. Why? How to group this query?

like image 345
Ivan Bosnic Avatar asked Nov 06 '08 12:11

Ivan Bosnic


People also ask

Can you GROUP BY an alias in Oracle?

In Oracle you cannot use an alias in a group by clause.

Can you GROUP BY alias?

Column Alias Column aliases can be used for derived columns. Column aliases can be used with GROUP BY and ORDER BY clauses.

Can you GROUP BY column alias in SQL?

A column alias may be used in the ORDER BY clause but not in the GROUP BY clause. So after the ORDER BY an expression is allowed, a position ( order by 1 ) or a c_alias which stands for "column alias". As you can see, no c_alias option after it, so you can't use a column alias.

Can we use alias in ORDER BY clause Oracle?

In ORDER BY you can refer to column aliases in the SELECT clause.


2 Answers

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

Grouping normally works if you repeat the respective expression in the GROUP BY clause. Just mentioning an alias is not possible, because the SELECT step is the last step to happen the execution of a query, grouping happens earlier, when alias names are not yet defined.

To GROUP BY the result of a sub-query, you will have to take a little detour and use an nested query, as indicated above.

like image 127
Tomalak Avatar answered Sep 22 '22 07:09

Tomalak


Nest the query with the alias column:

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; 
like image 35
Tony Andrews Avatar answered Sep 20 '22 07:09

Tony Andrews