简体   繁体   English

在 SQL 中使用 HAVING 子句

[英]Using the HAVING clause in SQL

I am trying to get the employees whose income is greater than 80% of the total average.我试图获得收入超过平均总收入 80% 的员工。 The problem is that the HAVING clause doesn't works as it throws the following error.问题是 HAVING 子句不起作用,因为它会引发以下错误。

This is the error in line of the HAVING (column 38):这是 HAVING(第 38 列)中的错误:
ORA-00935: group function is nested too deeply ORA-00935: 组函数嵌套太深

How can I fix the query to use HAVING correctly?如何修复查询以正确使用 HAVING?

SELECT 
  e.FIRST_NAME || ' ' || e.LAST_NAME as name,
  sum(o.order_total) as income
FROM  EMPLOYEES e, ORDERS o
WHERE e.employee_id = o.sales_rep_id 
GROUP BY e.FIRST_NAME, e.LAST_NAME
HAVING sum(o.order_total)*0.8 > avg(sum(o.order_total))
ORDER BY sum(o.order_total) DESC;

Starting from your existing query, you could use a window function to compute that grand average, and use it for filtering in the having clause:从您现有的查询开始,您可以使用窗口函数来计算该总平均值,并将其用于在having子句中进行过滤:

select 
    e.first_name || ' ' || e.last_name name,
    sum(o.order_total) income
from employees e
inner join orders o on e.employee_id = o.sales_rep_id 
group by e.employee_id, e.first_name, e.last_name
having sum(o.order_total) > 0.8 * avg(sum(o.order_total)) over()
order by sum(o.order_total) desc;

Notes:笔记:

  • always use explicit joins (with the on keyword) rather than old-school, implicit joins始终使用显式连接(使用on关键字)而不是老式的隐式连接
  • I added the id of the employee to the group by clause to prevent wrongly grouping possible homonyms我将员工的 id 添加到group by子句中,以防止错误地将可能的同音异义词分组

Alternatively, you can use a subquery:或者,您可以使用子查询:

select name, income
from (
    select 
        e.first_name || ' ' || e.last_name name,
        sum(o.order_total) income,
        avg(sum(o.order_total)) over() avg_income
    from employees e
    inner join orders o on e.employee_id = o.sales_rep_id 
    group by e.employee_id, e.first_name, e.last_name
) t
where income > 0.8 * avg_income
order by income desc;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM