作为where子句的Oracle SQL选择组函数

k5ifujac  于 2023-02-07  发布在  Oracle
关注(0)|答案(2)|浏览(227)

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

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

现在,我只想得到一个结果,上述SQL如果所有雇员的工资总额的位置是超过1.000.000欧元。否则,结果应该是空。
我创建了一个select语句,它分析所有雇员的总和并返回NULL或超过1.000.000欧元的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不是单组组函数

6za6bjd0

6za6bjd01#

您选择了非聚合字段,但未使用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
hmae6n7t

hmae6n7t2#

或者,如果希望按地点列出的sum(emp_salary)〉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;

相关问题