为mysql中的每个人获得第二高的薪水

u0sqgete  于 2021-06-25  发布在  Mysql
关注(0)|答案(5)|浏览(233)

我们有下面的table

person_id  |    salary
   1       |     1500
   1       |     1000
   1       |      500
   2       |     2000
   2       |     1000
   3       |     3000
   3       |     2000
   4       |     3000
   4       |     1000

我们希望每个人的薪水都是第二高的。按每个人分组,获得第二高的工资。就像下面一样

person_id  |    salary
   1       |     1000
   2       |     1000
   3       |     2000
   4       |     1000

提前感谢:)

dgjrabp2

dgjrabp21#

通过使用聚合函数和self-join,您可以执行以下操作

select a.*
from demo a
left join demo b on a.person_id = b.person_id
group by a.person_id,a.salary
having sum(a.salary < b.salary) = 1 /* 0 for highest 1 for second highest 2 for third and so on ... */

或者在 sum ```
having sum(case when a.salary < b.salary then 1 else 0 end) = 1

演示
请注意,这并不能像一个人可能有两个相同的薪资值一样处理关系,我假设一个人的每个薪资值将不同于另一个人的其他薪资值来处理@juergen d提到的这种case方法将与其他case语句一起工作
nzkunb0c

nzkunb0c2#

这里有一种方法 exists 以及 having 条款

SELECT person_id,
       Max(salary)
FROM   Yourtable a
WHERE  EXISTS (SELECT 1
               FROM   Yourtable b
               WHERE  a.person_id = b.person_id
               HAVING ( a.salary < Max(b.salary)
                        AND Count(*) > 1 )
                       OR Count(Distinct salary) = 1)
GROUP  BY person_id
62lalag4

62lalag43#

另一种方式 JOIN .
查询

select t1.`person_id`, max(coalesce(t2.`salary`, t1.`salary_1`)) as `salary_2` from(
   select `person_id`, max(`salary`) as `salary_1`
   from `your_table_name`
   group by `person_id`
) t1
left join `your_table_name` t2
on t1.`person_id` = t2.`person_id`
and t1.`salary_1` <> t2.`salary`
group by t1.`person_id`;

在这里找到一个SQLFiddle演示

ghg1uchk

ghg1uchk4#

你也可以用

select max(salary), person_id
from (select salary, person_id from demo 
      except 
      (select max(salary), person_id from demo group by person_id)) s
group by person_id

从初始数据集中删除每个人的最高工资,然后重新开始。

093gszye

093gszye5#

尝试

select t1.*
from your_table t1
join
(
    select person_id,
           @rank := case when person_id = @prevPersonId then @rank + 1 else 1 end as rank,
           @prevPersonId := person_id
    from your_table
    cross join (select @rank := 0, @prevPersonId := 0) r
    group by person_id
    order by person_id asc, salary desc
) t2 on t1.person_id = t2.person_id
where rank = 2

相关问题