如果第二高薪不可用,如何明智地获得第二高薪部门然后显示第一高薪?
how to get second highest salary department wise if second highest salary not available then display first higest salary?
如果部门只有一个工资,如何找到工资第二高的部门,然后显示第一高的工资。
输入为
dept_id salary
10 500
10 600
10 1000
20 800
20 900
20 200
30 1200
输出
dept_id salary
10 600
20 800
30 1200
您可以使用 window 函数:
select dept_id, salary
from (
select
t.*,
row_number() over(partition by dept_id order by salary desc) rn,
count(*) over(partition by dept_id) cnt
from mytable t
) t
where rn = 2 or (rn = 1 and cnt = 1)
该子查询按薪水递减对同一部门的记录进行排序,并计算每个部门有多少员工。然后您可以使用此信息在外部查询中进行过滤。
如果部门只有一个工资,如何找到工资第二高的部门,然后显示第一高的工资。 输入为
dept_id salary
10 500
10 600
10 1000
20 800
20 900
20 200
30 1200
输出
dept_id salary
10 600
20 800
30 1200
您可以使用 window 函数:
select dept_id, salary
from (
select
t.*,
row_number() over(partition by dept_id order by salary desc) rn,
count(*) over(partition by dept_id) cnt
from mytable t
) t
where rn = 2 or (rn = 1 and cnt = 1)
该子查询按薪水递减对同一部门的记录进行排序,并计算每个部门有多少员工。然后您可以使用此信息在外部查询中进行过滤。