找到每个部门的第二高薪

时间:2016-02-01 01:26:58

标签: sql-server

您好我有一个架构员工(员工,姓名,离职,工资)。我想找出每个部门的第二高薪。

     [HttpPost]
     public async Task<ActionResult> ConvertWav(int id)
     {
       using (var c = new DbEntities())
           {
              var converter = new FFMpegConverter();
              //code which converting some files from the path which the take from the DB 
              //and put it in the local directory
           }
     }

这可以完成工作,但如果某个部门只有1名员工,那么它就不会打印出该工资。谁能帮帮我呢?

1 个答案:

答案 0 :(得分:1)

试试这个

使用Count() over()分析函数计算每个部门的记录。当计数为1时,请取等级1

SELECT departmentid, 
       NAME, 
       salary 
FROM   (SELECT departmentid, 
               NAME, 
               salary, 
               Dense_rank()OVER (partition BY departmentid 
                              ORDER BY salary DESC) AS Rank, 
               Count(1)OVER(partition BY departmentid) AS cnt 
        FROM   employee)t 
WHERE  t.rank = 2 
        OR ( t.rank = 1 
             AND cnt = 1 ) 

注意:我使用DENSE_RANK而不是RANK,因为当第一个薪水中有 TIE 时,您将无法获得{{1} }}