【问题标题】:Invalid identifier when use alternate name of column使用列的备用名称时标识符无效
【发布时间】:2020-10-13 17:36:09
【问题描述】:

我有一些代码行,但它不会以某种方式工作。我想将此列称为 round() 名称“Diem”以供以后使用,但 Diem >= 1 使其成为无效标识符。有人可以帮忙吗?

select id, name, round(avg(
decode(grade, 'A+', 4.5,'A', 4,
'A-',3.5, 'B+',3, 'B',2.5, 'B-', 2,
'C+', 1.5, 'C', 1, 'C-',0.5
)), 1) as ***DIEM***
from takes t join student s 
using (id)
where tot_cred >= 128
and ***DIEM*** >= 1
group by id, name;

【问题讨论】:

    标签: sql oracle join select average


    【解决方案1】:

    您想要过滤聚合函数的结果:为此,您需要使用having 子句而不是where 子句。

    此外,您不能访问在 where 子句中的 select 子句中定义的别名(也不能在 Oracle 中的 having 子句中)。

    您需要重复表达式或使用派生表(子查询或 cte)。

    select 
        id, 
        name, 
        round(avg(decode(grade, 'A+', 4.5,'A', 4, ...)), 1) as diem
    from takes t 
    inner join student s using (id)
    where tot_cred >= 128
    group by id, name
    having round(avg(decode(grade, 'A+', 4.5,'A', 4, ...)), 1) >= 1
    

    在这里,将解码移动到子查询可能更简单。假设grades 来自takes 表:

    select 
        id, 
        name, 
        round(avg(t.new_grade), 1) as diem
    from (
        select t.*, decode(grade, 'A+', 4.5, 'A', 4, ...) as new_grade
        from takes t
    ) t 
    inner join student s using (id)
    where tot_cred >= 128
    group by id, name
    having round(avg(t.new_grade), 1) >= 1
    

    【讨论】:

    • 谢谢。第一个有效,但我仍然不能用短名称调用 round()。第二个完全符合我的要求,“new_grade”无效标识符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    相关资源
    最近更新 更多