简体   繁体   English

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

[英]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. 我正在尝试运行查询,我在select语句中使用子查询。
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. 这与ORA 00923失败:从找不到预期错误的关键字。 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. SysDate是保留关键字。 Although, COUNT is an aggregate function but it is permitted to be used. 虽然, COUNT是一个聚合函数,但允许使用它。

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. 您在代码中唯一的错误是使用关键字sysdate并将其计为别名,这是禁止的......使用AS也是可选的。 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. 使用计数是可以的,但在现实世界中,这是不可取的,并且pro-s不会使用关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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