[英]Get second highest salary for each person in mysql
我們有如下表
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
提前致謝 :)
通過使用聚合函數和自連接,您可以執行以下操作
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提到的這種情況方法將適用於其他情況聲明
這是一種使用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
嘗試
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
圍繞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`;
您也可以使用
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
從初始數據集中刪除每個人的最高薪水,然后重新開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.