由于列别名导致oracle中的标识符无效错误

Set*_*iei 6 sql oracle

我有一个查询如下

select t.col1,
 t.col2,
 (select count(col1)
  from tab 
  where col1 = t.col1
        and col2 = t.col2
   ) as col3 
from tab t
where col3 > 1
Run Code Online (Sandbox Code Playgroud)

该查询给出了"col3无效标识符"错误.

我尝试了不同的变体来定义我在下面给出的别名以及我在使用它时得到的错误

  1. select t.col1,
           t.col2,
           (select count(col1)
            from tab 
            where col1 = t.col1
              and col2 = t.col2
           ) as "col3" 
    from tab t
    where col3 > 1
    
    Run Code Online (Sandbox Code Playgroud)

错误:col3无效标识符

  1. select t.col1,
           t.col2,
           (select count(col1)
            from tab 
            where col1 = t.col1
              and col2 = t.col2
            ) as 'col3' 
    from tab t
    where [col3] > 1
    
    Run Code Online (Sandbox Code Playgroud)

错误:在哪里丢失表达式

  1. select t.col1,
           t.col2,
           (select count(col1)
            from tab 
            where col1 = t.col1
              and col2 = t.col2
           ) "col3" 
    from tab t
    where [col3] > 1
    
    Run Code Online (Sandbox Code Playgroud)

错误:在哪里丢失表达式

请解释我的错误是什么

PS我不知道为什么我无法在这里将查询示例标记为代码.我为这些查询的可读性差而道歉

a_h*_*ame 6

您的主要问题是您无法在相同的"嵌套级别"上访问列别名.为了能够使用别名,您需要将整个查询包装在派生表中:

select *
from (
  select t.col1,
         t.col2,
         (select count(col1)
          from tab 
          where col1 = t.col1
            and col2 = t.col2
         ) as col3 
  from tab t
) 
where col3 > 1
Run Code Online (Sandbox Code Playgroud)

您的"编号"示例不会有两个原因:首先是出于上述原因,其次是因为使用双引号引用的标识符区分大小写.所以"col3"是一个不同的列名"Col3".由于Oracle将不带引号的标识符折叠为大写(符合SQL标准的要求)col3,因此等效于"COL3"

最后:[col3]在SQL中是无效的标识符,无论您是否将其用作列别名.必须使用双引号引用标识符.这些方括号在SQL中无效