Oracle pl/sql中的group by子句不能使用别名,应该这样写。

17 篇文章 0 订阅
9 篇文章 0 订阅


下面的语句执行的话会报错:ORA-00904: "CALLT": 标示符无效

select case when ta.call_time = 0 then 0
    when ta.call_time <= 6 and ta.call_time > 0 then 1
    when ta.call_time <= 60 and ta.call_time > 6 then 2
    when ta.call_time <= 3600 and ta.call_time > 60 then 3
    else 4 end as callt,
      count(ta.annoyanceid) as counts 
from t_annoyance ta
group by callt;

这是因为在SQL执行的时候,WHERE和GROUP语句在字段分类之前就已经执行了,在此期间,别名还没有生效,因此找不到指定别名的字段,报错。


除了聚合函数之外的表达式不仅仅是一个字段,所以用别名代替,这种情况怎么写呢?有三种方法。

方法一,只写表达式中存在的字段

select case when ta.call_time = 0 then 0
    when ta.call_time <= 6 and ta.call_time > 0 then 1
    when ta.call_time <= 60 and ta.call_time > 6 then 2
    when ta.call_time <= 3600 and ta.call_time > 60 then 3
    else 4 end as callt,
      count(ta.annoyanceid) as counts 
from t_annoyance ta
group by ta.call_time;


方法二,将表达式都写入group by子句

select case when ta.call_time = 0 then 0
    when ta.call_time <= 6 and ta.call_time > 0 then 1
    when ta.call_time <= 60 and ta.call_time > 6 then 2
    when ta.call_time <= 3600 and ta.call_time > 60 then 3
    else 4 end as callt,
      count(ta.annoyanceid) as counts 
from t_annoyance ta
group by case when ta.call_time = 0 then 0
    when ta.call_time <= 6 and ta.call_time > 0 then 1
    when ta.call_time <= 60 and ta.call_time > 6 then 2
    when ta.call_time <= 3600 and ta.call_time > 60 then 3
    else 4 end;


方法三,将表达式放入子查询

select t1.callt,
      count(t2.annoyanceid) as counts 
from (<strong>select case when ta.call_time = 0 then 0
    when ta.call_time <= 6 and ta.call_time > 0 then 1
    when ta.call_time <= 60 and ta.call_time > 6 then 2
    when ta.call_time <= 3600 and ta.call_time > 60 then 3
    else 4 end as callt
      , ta.annoyanceid 
      from t_annoyance ta) t1
      , t_annoyance t2
where t1.annoyanceid = t2.annoyanceid
group by t1.callt;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值