【问题标题】:Oracle SQL select group function as where clauseOracle SQL 选择组函数作为 where 子句
【发布时间】:2023-02-07 22:55:52
【问题描述】:

我有一个简单的SQL,结果是员工的基本信息。

select emp_name, emp_firstname, emp_location, emp_salary from employees e
where e.emp_location = 'XYZ'

现在,如果该地点所有员工的工资总和超过 1.000.000 欧元,我只想获得上述 SQL 的结果。否则结果应该为 NULL。

我创建了一个 select 语句,它确实分析了所有员工的总和并返回 NULL 或超过 1.000.000 EUR 的 SUM 值:

select sum(emp_salary) from employees e
where e.emp_location = 'XYZ'
having sum(emp_salary) > 1000000

当我现在尝试组合这两个 SQL 时:

select emp_name, emp_firstname, emp_location, emp_salary from employees e
where e.emp_location = 'XYZ'
having sum(emp_salary) > 1000000

我收到错误 ORA-00937 not a single-group group function

【问题讨论】:

  • 您选择了非聚合字段,但没有使用 GROUP BY 子句。那是你的问题。

标签: sql oracle


【解决方案1】:

您选择了非聚合字段,但没有使用 GROUP BY 子句。通过修复它,您的查询应该可以正常工作:

SELECT emp_name, emp_firstname, emp_location, SUM(emp_salary) AS emp_salary 
FROM employees
WHERE emp_location = 'XYZ' 
GROUP BY emp_name, emp_firstname, emp_location
HAVING SUM(emp_salary) > 1000000

【讨论】:

    【解决方案2】:

    或者,如果您希望 sum(emp_salary) by location>1000000,则:

    with tb_sal_loc as (
    select emp_name, emp_firstname, emp_location, emp_salary 
      ,sum(emp_salary) over (partition by emp_location) loc_salaries
    from employees e
    where e.emp_location = 'XYZ')
    select *
    from b_sal_loc
    where loc_salaries>1000000;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多