【问题标题】:why query is showing 'invalid relational operator'为什么查询显示“无效的关系运算符”
【发布时间】:2020-08-28 22:27:22
【问题描述】:
select * 
from employees
 where department_id,salary in (
    select department_id,max(salary) 
    from employees group by department_id
 )

【问题讨论】:

    标签: sql oracle group-by max greatest-n-per-group


    【解决方案1】:

    您想要元组比较 - 您需要用括号将 in 左侧的列元组括起来:

    select * 
    from employees 
    where (department_id,salary) in (
        select department_id, max(salary) from employees group by department_id
    )
    

    请注意,这个 top-1-per-group 查询可以使用窗口函数更有效地表达:

    select *
    from (
        select e.*, rank() over(partition by department_id order by salary desc nulls last) rn
        from employees e
    ) t
    where rn = 1
    

    【讨论】:

    • 我们应该希望SALARY 永远不会是null - 如果可以,null 行将在订购desc 时排在第一位。这是使用降序时的默认值。为了安全起见,我们应该在order by salary desc 之后添加nulls last 选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 2014-09-17
    • 2018-08-07
    • 1970-01-01
    • 2018-01-01
    相关资源
    最近更新 更多