使用聚合函数mySQL时,我不断收到错误消息

时间:2020-04-16 15:30:47

标签: mysql average aggregate-functions

关于以下原因为何不起作用的任何想法。 该表称为收入,它具有3个列,分别为姓名,部门和薪水。我想获得营销部门人员的姓名和工资,该人员的工资低于所有员工的平均工资。 当我运行以下命令时,出现错误1111。

SELECT name, salary
FROM income
WHERE dept = "marketing"
HAVING salary < AVG(salary)

2 个答案:

答案 0 :(得分:1)

您必须在WHERE子句中使用子查询来返回平均值:

SELECT name, salary
FROM income
WHERE dept = 'marketing'
AND salary < (SELECT AVG(salary) FROM income WHERE dept = 'marketing') 

如果所有雇员是指所有部门的雇员的平均薪水,则从子查询中删除WHERE dept = 'marketing'

答案 1 :(得分:1)

作为将子查询放在WHERE子句中的替代方法,我们可以使用内联视图:

SELECT t.name
     , t.salary
  FROM ( SELECT AVG(d.salary) AS avg_salary
           FROM income d
          WHERE d.dept = 'marketing'
       ) a
  JOIN income t
    ON t.salary > a.avg_salary
   AND t.dept   = 'marketing'

使用内联视图,我们还可以返回平均工资,并且可以计算多个部门之间的差异,甚至是百分比差异

在查询上进行一些扩展,如下所示:

SELECT a.dept
     , t.name
     , t.salary
     , a.avg_salary
     , ((t.salary - a.avg_salary) / a.avg_salary) * 100.0 AS pct_greater 
  FROM ( SELECT d.dept
              , AVG(d.salary) AS avg_salary
           FROM income d
          GROUP
             BY d.dept
       ) a
  JOIN income t
   AND t.dept   = a.dept
    ON t.salary > a.avg_salary
 ORDER
    BY a.dept
     , t.salary DESC