Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 SQL query question

Author  Topic 

sixsigma1978
Starting Member

25 Posts

Posted - 2009-11-24 : 17:55:00
All,
Am new to SQL and need help with the following:
I have a table "company" thats defined like this

Company

Department Employee Salary
~~~~~~~~~~~ ~~~~~~~~ ~~~~~~
AAA Emp1 1000
AAA Emp2 3000
BBB Emp3 5000
BBB Emp4 9000

I'd like to find the employee with the MAXIMUM salary in every department. I couldn't figure out how to this.
Any suggestions?

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-11-24 : 18:24:02
Sounds like a homework question, but I'll bite.

SELECT c.Department, c.Employee, c.Salary
FROM Company c
JOIN (SELECT Department, MAX(Salary) AS Salary FROM Company GROUP BY Department) t
ON c.Department = t.Department AND c.Salary = t.Salary

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

"Let's begin with the premise that everything you've done up until this point is wrong."
Go to Top of Page

sixsigma1978
Starting Member

25 Posts

Posted - 2009-11-24 : 18:30:42
Nope - Not a homework question !! (Though obviously I've got no way to prove it : ergo - faith!!) :)

Thanks for the feedback - I didn't understand the SQL but i'll dissect it - best way to learn IMO!!

Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-11-24 : 18:32:49
You're welcome. My solution is a using a derived table, which come in handy for GROUP BYs like you have.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

"Let's begin with the premise that everything you've done up until this point is wrong."
Go to Top of Page
   

- Advertisement -