美文网首页我爱编程
LC-mysql-185( Department Top Thr

LC-mysql-185( Department Top Thr

作者: SolaTyolo | 来源:发表于2018-04-15 22:25 被阅读0次

    本SQL问题是 #184. Department Highest Salary

    解决本地主要是利用了mysql 实现rank

    已下代码即可实现同DepartmentId内的根据Salary的rank

    select l.*,
    @rank := (case when @pre = l.Salary and @cur = l.DepartmentId then @rank when @cur != l.DepartmentId then 1  else @rank+1 end) as rank,
    @cur :=  l.DepartmentId as cur,
    @pre:=  l.Salary as pre
    from (
      select * from Employee as e order by e.DepartmentId ,e.Salary desc
    )l,(select @pre :=0 ,@cur := 0,@rank := 0)t
    
    

    完整SQL如下:

    select d.Name as Department,
          k.Name as Employee,
          k.Salary as Salary
    from Department as d
    join(
    select ee.Name,ee.Salary,ee.DepartmentId from (
    select l.*,
    @rank := (case when @pre = l.Salary and @cur = l.DepartmentId then @rank when @cur != l.DepartmentId then 1  else @rank+1 end) as rank,
    @cur :=  l.DepartmentId as cur,
    @pre:=  l.Salary as pre
    from (
      select * from Employee as e order by e.DepartmentId ,e.Salary desc
    )l,(select @pre :=0 ,@cur := 0,@rank := 0)t)ee 
      where ee.rank < 4)k ON d.Id = k.DepartmentId
    

    相关文章

      网友评论

        本文标题:LC-mysql-185( Department Top Thr

        本文链接:https://www.haomeiwen.com/subject/jcbjkftx.html