简体   繁体   中英

How to add column alias to subquery in select statement?

I am trying to run a query where I am using subqueries in the select statement.
This works:

select   
(select sysdate from dual),   
(select 'municipality' from dual),  
(select count(*) from municipality)  
from dual;  

But the resulting columnnames are ugly and therefore I want to add the column aliases.

I am trying to run the following query:

select   
(select sysdate from dual) as sysdate,   
(select 'municipality' from dual) as tablename,  
(select count(*) from municipality) as count  
from dual;

This fails with the ORA 00923: From keyword not found where expected error. Somehow, I am missing something.

Any suggestions?

Thanks.

try wrapping it with double quotes,

select
   (select sysdate from dual) as "sysdate",
   (select 'municipality' from dual) as "tablename",
   (select count(*) from municipality) as "count"
from dual;

SysDate is a reserved keyword. Although, COUNT is an aggregate function but it is permitted to be used.

The only error you had in your code was using keywords sysdate and count as aliases, which is no-no... Using AS is optional also. This works as intended:

select   
 (select sysdate from dual)  s_date,            -- NOT sysdate
 (select 'municipality' from dual)  tablename,  
 (select count(*) from dual) as cnt             -- NOT count
 from dual;

It is OK to use count but in real world it is not advisable and pro-s would not use keywords.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM