views:

190

answers:

5

I have the relation instructor(ID, name, dept_name, salary).

How would I go about finding the name of the department with the highest average salary?

+3  A: 

looks like a job for the HAVING clause

Silvio Donnini
Something along the lines of:having avg(salary) > ?
Doug
+1  A: 

will this do the trick?

select top 1 id, name, avg (salary)
from instructor
group by id, name
order by avg (salary) desc
Raj More
No. I can get the averages of all the department's by using:select dept_name, avg(salary)from instructorgroup by dept_nameBut I can't select the highest average salary department from there.
Doug
You can "order by desc avg(salary) limit 1" to see the highest.
Don
select dept_name from instructorgroup by dept_nameorder by avg(salary) desc limit 1 Gives me an error "SQL command not properly ended"
Doug
I am using Oracle SQL, however trying to use having rownum=1 still results in the same error.
Doug
top 1 is TSQL; limit 1 is used in MySQL. My earlier comment with "having rownum=1" is incorrect, see http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html for the full details. If you are using Oracle, you will have to do something like: select * from (select dept_name, avg(salary) from instructor group by dept_name order by avg(salary)) where ROWNUM = 1
James
Tweaked that a little bit, but that got it, thanks!
Doug
A: 

Given the homework tag, I won't spell it out for you, but you want to look into the AVG function and the GROUP BY clause.

David Hedlund
It is indeed homework, my mistake for not tagging it as such, but I've been working on it quite a bit and just can't figure it out.
Doug
A: 
select top 1 dept_name, avg(salary) as AvgSalary
from instructor
group by dept_name
order by AvgSalary desc
RedFilter
A: 

This will get you both if two deparments have the same average salary, use rownum=1 if this is not needed.

with averages as (select dept_name,avg(salary) aver from instructor group by dept_name) select dept_name from averages where aver = (select max(aver) from averages)

John Ormerod