Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
See more:
Hi Friends,

I am having two tables 1) EMP and 2) DEPT

EMP table :
Empid Ename Esal deptId
1 raju 10000 10
2 rani 50000 20
3 pavan 7000 10
4 kumar 8000 30

DEPT table:
Deptid Dname
10 IT
20 Non IT
30 HR


I want output: Highest Salary department wise along wit department name and emp details
Like as follows:

Empid Ename Esal DName
1 raju 10000 IT
2 rani 50000 Non IT
4 kumar 8000 HR

Please suggest me with best query :)

Thanks & Regards
Syed Chand Basha
Posted

1 solution

Assuming you don't care about ties, something like this should work:
SQL
WITH RankedEmployees As
(
    SELECT
        EmpId,
        EmpName,
        Esal,
        DeptId,
        ROW_NUMBER() OVER (PARTITION BY DeptId ORDER BY Esal DESC) As RN
    FROM
        Emp
)
SELECT
    E.EmpId,
    E.EmpName,
    E.Esal,
    D.DName
FROM
    Dept As D
    INNER JOIN RankedEmployees As E
    ON E.DeptID = D.DeptId
    And E.RN = 1
;

If you do want to show ties, replace ROW_NUMBER with RANK.

ROW_NUMBER[^]
RANK[^]
 
Share this answer
 
Comments
chand5055 5-Feb-15 2:08am    
Thank you Richard Deeming.... Its working perfect.... :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900