如何在select语句中向子查询添加列别名?

时间:2013-02-14 13:27:55

标签: sql oracle select alias

我正在尝试运行查询,我在select语句中使用子查询 这有效:

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

但是生成的列名很难看,因此我想添加列别名。

我正在尝试运行以下查询:

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

这与ORA 00923失败:从找不到预期错误的关键字。 不知怎的,我错过了一些东西。

有什么建议吗?

感谢。

2 个答案:

答案 0 :(得分:2)

尝试用双引号包装它,

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

SysDate是保留关键字。虽然COUNT是一个聚合函数,但允许使用它。

答案 1 :(得分:1)

您的代码中唯一的错误是使用关键字sysdate并将其计为别名,这是禁忌...使用AS也是可选的。这按预期工作:

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

使用计数是可以的,但在现实世界中,这是不可取的,并且pro-s不会使用关键字。