how to get second highest salary department wise without using analytical functions?

前端 未结 11 2015
孤独总比滥情好
孤独总比滥情好 2021-01-06 03:08

Suppose we have 3 employees in each department.we have total 3 departments . Below is the sample source table

Emp deptno salary
A    10     1000
B    10              


        
11条回答
  •  时光取名叫无心
    2021-01-06 03:47

    On MySQL this how you can get second highest salary, given table name is salaries:

    By Nested Queries: (where you can change offset 0/1/2 for first, second and third place respectively)

    select
      *
    from
      salaries as t1 
    where 
      t1.salary = (select 
                   salary
                 from 
                   salaries
                 where 
                 salaries.deptno = t1.deptno ORDER by salary desc limit 1 offset 1);
    

    or might be by creating rank: (where you can change rank= 1/2/3 for first, second and third place respectively)

    SET @prev_value = NULL;
    SET @rank_count = 0;
    select * from 
    (SELECT
      s.*, 
      CASE 
          WHEN @prev_value = deptno THEN @rank_count := @rank_count + 1
          WHEN @prev_value := deptno THEN @rank_count := 1 
          ELSE @rank_count := 1 
      END as rank
    FROM salaries s
    ORDER BY deptno, salary desc) as t
    having t.rank = 2;
    

提交回复
热议问题