【问题标题】:Using the HAVING clause in SQL在 SQL 中使用 HAVING 子句
【发布时间】:2020-03-07 23:40:01
【问题描述】:

我正在努力寻找收入超过平均总收入 80% 的员工。问题是 HAVING 子句不起作用,因为它会引发以下错误。

这是 HAVING 行中的错误(第 38 列):
ORA-00935: group 函数嵌套太深

如何修复查询以正确使用 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;

【问题讨论】:

  • 我删除了冲突的数据库标签。请仅添加相关的 - 答案可能取决于您使用的软件。
  • “不起作用”是什么意思?是不是你有一个逗号,你应该有一个小数点?是别的吗?如果是这样,是什么?请edit您的问题包括一些示例数据、您对该示例数据的预期结果以及您的代码的问题/错误。

标签: sql oracle group-by oracle-apex


【解决方案1】:

从您现有的查询开始,您可以使用窗口函数来计算该总平均值,并将其用于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;

注意事项:

  • 始终使用 显式 连接(使用 on 关键字)而不是老式的隐式连接
  • 我在group by 子句中添加了员工的id,以防止错误地对可能的同音词进行分组

或者,您可以使用子查询:

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;

【讨论】:

  • 这似乎给了ORA-00935: group function is nested too deeply
  • 同一行出错(第 38 列): > ORA-00935: 组函数嵌套太深 > 00935. 00000 - “组函数嵌套太深”
  • @MT0:我的错,我对窗口函数太有野心了。我在我的答案中添加了第二个更合理的查询...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
相关资源
最近更新 更多