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.
| Author |
Topic |
|
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2003-09-08 : 07:15:34
|
| Marimuthu writes "i want a query that returns n th max salary of the employee with respective to their departmentfor eg.if the emp table looks like this empid empname empsal empdept1 Alex 15000 12 Sonia 20000 13 Edwin 50000 14 Thomas 30000 25 Peter 20000 26 John 34000 27 Johnson 55000 38 Peterson 20300 3for the 2nd max empsal the o/p should be like thisempid empname empsal empdept2 Sonia 20000 14 Thomas 30000 28 Peterson 20300 3mail me asapRegards" |
|
|
dsdeming
479 Posts |
Posted - 2003-09-08 : 08:34:48
|
| You need something like:SET ROWCOUNT 2SELECT TOP 1 t.empid, t.empsalFROM ( SELECT * FROM emp ORDER BY empsal ) tORDER BY t.empsal DESCSET ROWCOUNT 0Dennis |
 |
|
|
jsmith8858
Dr. Cross Join
7423 Posts |
Posted - 2003-09-08 : 13:51:08
|
First, you need to decide how to handle ties. In this example, we will say that if the salary is the same, then the person with the lowest EmpID gets precedence.select E.*, (select count(*) from Salaries s2 where s.empDept = s2.empDept and (s2.empSal > s1.empSal OR (s2.empSal = S1.EmpSal and S2.EmpID <= S1.EmpID))) as DeptRankFROM Salaries s1 Note how the confusing WHERE ranks each employee based on their salary in relation to their dept, and how it handles ties.Then, to return the #2 salary from each dept, you just:SELECT * FROM (aboveSQL) aWHERE DeptRank = 2 - Jeff |
 |
|
|
dsdeming
479 Posts |
Posted - 2003-09-09 : 08:17:12
|
Good point, Jeff. I wasn't handling ties at all. And to think, you did all that without using a cross join. Dennis |
 |
|
|
only333
Starting Member
1 Post |
Posted - 2011-06-01 : 04:10:15
|
quote: Originally posted by jsmith8858 First, you need to decide how to handle ties. In this example, we will say that if the salary is the same, then the person with the lowest EmpID gets precedence.select E.*, (select count(*) from Salaries s2 where s.empDept = s2.empDept and (s2.empSal > s1.empSal OR (s2.empSal = S1.EmpSal and S2.EmpID <= S1.EmpID))) as DeptRankFROM Salaries s1 Note how the confusing WHERE ranks each employee based on their salary in relation to their dept, and how it handles ties.Then, to return the #2 salary from each dept, you just:SELECT * FROM (aboveSQL) aWHERE DeptRank = 2 - Jeff
Amazing! Thanks a million Jeff for sharing. |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
|
|
|
|
|
|
|