如何在部门中找到第二高工资如果部门中只有一个工资,则显示第一高工资。作为输入
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
您可以使用窗口函数:
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)
子查询通过降低工资对具有相同部门的记录进行排名,并统计每个部门有多少员工。然后,您可以使用这些信息在外部查询中进行筛选。