0

I've a table like this:

+----+------+--------+
| id | name | salary |
+----+------+--------+
|  1 | Ajay |  20000 |
|  2 | Aja  |   2000 |
|  3 | Aj   |    200 |
|  4 | A    |   3000 |
|  5 | q    |  30000 |
+----+------+--------+  

I want to write a query that can print highest salary, medium salary and lowest salary. So I wrote this query:

select salary 
  from parent
 where max(sal) 
    && salary < ( SELECT MAX( salary )
                   FROM parent ) 
    && min(salary);  

And mysql returned an error:

ERROR 1111 (HY000): Invalid use of group function  

what is the correct query?

1
  • 1
    what do you try to achieve? Commented May 1, 2015 at 12:54

2 Answers 2

2

MySQL doesn't offer an aggregate function to grab a median value, sorry to say. Hopefully you can go with the average (the arithmetic mean) value.

Stuff like MAX(), MIN(), and AVG() (called aggregate functions in the jargon of SQL) can't appear in WHERE clauses. They can show up in SELECT and HAVING clauses. That's why you got an error.

You'll be wanting

SELECT MAX(salary) max_salary, 
       AVG(salary) avg_salary,
       MIN(salary) min_salary
  FROM parent

If you control your own MySQL server and you have a few MySQL dba chops, you can install a user-defined function to compute the median value. (If you're using a hosting service with a multitenant MySQL server, forget about this.) Read this.

http://mysql-udf.sourceforge.net/

Sign up to request clarification or add additional context in comments.

1 Comment

As an aside, median UDFs and sprocs are available.
0

select 'min' as k, min(salary) as v from parent union select 'avg' as k, avg(salary) as v from parent union select 'max' as k, max(salary) as v from parent

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.