jQuery in Action, 3rd edition
The moose likes JDBC and Relational Databases and the fly likes SQL query help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "SQL query help" Watch "SQL query help" New topic

SQL query help

Pawanpreet Singh
Ranch Hand

Joined: Jun 12, 2005
Posts: 264

I have table with columns as name, deptno and salary.

I need to get the names which has maximum salary in their deptmenets.

I could able to find maximum salaries in each department using

select depno, max(sal) from emp GROUP BY deptno;

But how to get correspodning names?

SCJP 5.0, SCWCD 1.4
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
Add "name" to the fields to be selected?

[edit]Add: That would probably work for a simple query, but you might need nested "selects" for anything more complicated.[/edit]
[ September 17, 2008: Message edited by: Campbell Ritchie ]
Shailesh Chandra
Ranch Hand

Joined: Aug 13, 2004
Posts: 1082

Which Database are you using ?

you can try this query, I haven't tested it

select name, depno, sal from emp where (depno, sal) in (
select depno, max(sal) from emp GROUP BY deptno)

[ September 17, 2008: Message edited by: Shailesh Chandra ]

Gravitation cannot be held responsible for people falling in love ~ Albert Einstein
I agree. Here's the link: http://aspose.com/file-tools
subject: SQL query help
It's not a secret anymore!