First two salaries in each department [duplicate]

十年热恋 提交于 2019-12-13 14:18:47

问题


I have a table called departments which consists of a column called salary. Now I want to have all the details of the highest two salaries in each department. How should we develop a query which yields the required output? Top-N analysis will give it as a whole but not for each department. I want the top two in each department.


回答1:


I realize you asked for this in Oracle. I can't help you there.

But, perhaps if you see the solution in MSSQL/TSQL it will help?

select 
     d.Salary
    ,d.Department
from
(
    select 
         r.Salary
        ,r.Department
        ,row_number() over(
            partition by r.Department
            order by r.Salary desc) as RowNumber
    from HumanResources as r
) as d
where d.RowNumber < 3

Best of luck!




回答2:


DECLARE @TV_SAL TABLE (EMPID INT, DEPTID CHAR(10),SAL INT)

INSERT INTO @TV_SAL(EMPID,DEPTID,SAL) VALUES(4,'OR',1004)    
INSERT INTO @TV_SAL(EMPID,DEPTID,SAL) VALUES(5,'OR',1005)    
INSERT INTO @TV_SAL(EMPID,DEPTID,SAL) VALUES(1,'OR',1001)    
INSERT INTO @TV_SAL(EMPID,DEPTID,SAL) VALUES(2,'OR',1002)    
INSERT INTO @TV_SAL(EMPID,DEPTID,SAL) VALUES(17,'CS',1503)    
INSERT INTO @TV_SAL(EMPID,DEPTID,SAL) VALUES(18,'CS',1503)    
INSERT INTO @TV_SAL(EMPID,DEPTID,SAL) VALUES(14,'CS',1500)    
INSERT INTO @TV_SAL(EMPID,DEPTID,SAL) VALUES(15,'CS',1501)

SELECT * 
  FROM @TV_SAL A     
 WHERE ( SELECT COUNT(DISTINCT(SAL)) 
           FROM @TV_SAL B
          WHERE A.SAL <= B.SAL 
            AND A.DEPTID = B.DEPTID
                ) <= 3 -- Replace this with 1 ,2 or n , n indicates top n   
 ORDER BY DEPTID, SAL DESC



回答3:


SELECT TOP 5 b.DepartName,a.Salary FROM Employee a

JOIN

Department b ON a.DepartId=b.DepartId

group by b.DepartName ORDER BY a.Salary DESC

It will working fine on Sql server and i am not aware about Oracle



来源:https://stackoverflow.com/questions/6600445/first-two-salaries-in-each-department

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!