有没有办法分组SQL函数?

时间:2016-09-29 14:57:13

标签: mysql sql

我想在SQL中对MIN()AVG()函数进行分组,即

  • MIN(AVG(column_name))
  • 或类似的东西。

有没有办法进行分组?

我试过了:

SELECT
      `instructer`.`dept_name`, AVG(`instructer`.`salary`)
AS
      MinAvgSalary
FROM
      `instructer`
GROUP BY
      `instructer`.`dept_name`
HAVING
      AVG(`instructer`.`salary`) = (SELECT MIN(AVG(`instructer`.`salary`)) FROM `instructer` GROUP BY `instructer`.`dept_name`)

但MySQL说:

  

1111 - 无效使用组功能

这是我的讲师表:

Enter image description here

3 个答案:

答案 0 :(得分:1)

您可以使用子选择

select t.dept_name, min(t.AvgSalary) AS MinAvgSalary 
from  (
  SELECT 
  `instructer`.`dept_name` AS dept_name
  , AVG(`instructer`.`salary`) AS       AvgSalary
  FROM  `instructer`
  GROUP BY `instructer`.`dept_name` ) t
GROUP BY t.dept_name
HAVING t.AvgSalary = min(t.AvgSalary)

答案 1 :(得分:1)

尝试在上一个查询中使用LIMIT 1

SELECT
      `instructer`.`dept_name`, AVG(`instructer`.`salary`)
AS
      MinAvgSalary
FROM 
      `instructer`
GROUP BY 
      `instructer`.`dept_name`
HAVING 
      AVG(`instructer`.`salary`) = 
     (SELECT AVG(`instructer`.`salary`) as AvgSalary
        FROM `instructer` 
        GROUP BY `instructer`.`dept_name` 
        ORDER BY AvgSalary LIMIT 1)

答案 2 :(得分:0)

如果其他人不工作,我做了很长的路。创建两个平均工资表(av1,av2),其中包含每个部门的平均工资。然后在新表(min1)中选择av1中的最低工资。然后在工资上加入min1到av2。您应该在av2中找到具有最低工资的记录,并且您也可以从那里提取部门名称:

SELECT av2.dept_name, av2.avsal
FROM
(SELECT MIN(avsal) as minsal
 FROM
 (SELECT dept_name, AVG(salary) as avsal
  FROM instructor
  GROUP BY dept_name) av1) min1
INNER JOIN
(SELECT dept_name, AVG(salary) as avsal
 FROM instructor
 GROUP BY dept_name) av2
ON min1.minsal = av2.avsal

在这里测试:http://sqlfiddle.com/#!9/77b0ac