Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to group SQL functions?

Tags:

sql

mysql

I want to group MIN() and AVG() function in SQL, that is,

  • MIN(AVG(column_name))
  • or something like that.

Is there a way to do the grouping?

I tried this:

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`)

But MySQL said:

1111 - Invalid use of group function

This is my instructor table:

Enter image description here

like image 800
Jahidul Islam Avatar asked Sep 29 '16 14:09

Jahidul Islam


2 Answers

You can use a subselect

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)
like image 169
ScaisEdge Avatar answered Oct 31 '22 21:10

ScaisEdge


Try to use LIMIT 1 in the last query:

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)
like image 43
valex Avatar answered Oct 31 '22 20:10

valex