Group by alias (Oracle)

后端 未结 5 1451
独厮守ぢ
独厮守ぢ 2020-11-28 08:07

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

select count(*), (select * from....) as alias_column 
from table 
group by alias_column
相关标签:
5条回答
  • 2020-11-28 08:33

    If you don't have to use an alias you could do it this way:

    select  
    EXTRACT(year from CURRENT_DATE), count(*) from something
    group by EXTRACT(year from CURRENT_DATE)
    order by EXTRACT(year from CURRENT_DATE)
    

    Instead of using alias and subquery.

    0 讨论(0)
  • 2020-11-28 08:39
    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.

    0 讨论(0)
  • 2020-11-28 08:42
    select count(*), (select * from....) as alias_column 
    from table 
    group by (select * from....)
    

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

    0 讨论(0)
  • 2020-11-28 08:42

    To use an alias in Oracle you need to ensure that the alias has been defined by your query at the point at which the alias is being used.

    The most straightforward way to do this is to simply treat the original query as a subquery -- in this case,

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

    becomes

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

    I can't speak to the performance implications, but it's very quick to write if you're trying to re-use an alias in your query - throw everything in parentheses and jump up a level...

    0 讨论(0)
  • 2020-11-28 08:51

    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;
    
    0 讨论(0)
提交回复
热议问题