如何使用SQLite按部门查找第n大薪水

How to find the nth largest salary by department using SQLite

假设所有员工及其部门都列在同一个 table employees 中。你会如何找到按部门排名第 n 大的工资?

我知道 this 让你很接近。

select SAL from EMPLOYEE E1 where 
 (N - 1) = (select count(distinct(SAL)) 
            from EMPLOYEE E2 
            where E2.SAL > E1.SAL )

但是添加 groupby 仍然不会让你到达那里,除非你在条件上进行了连接?

select SAL from EMPLOYEE E1

where 
 (N - 1) = (select count(distinct(SAL)) 
            from EMPLOYEE E2 
            inner join EMPLOYEE E3 ON department_id
            where E2.SAL > E3.SAL )
groupby department

如果这是家庭作业并且您必须使用关联子查询,那么您还必须关联 department:

SELECT DISTINCT e1.department, e1.SAL 
FROM EMPLOYEE e1 
WHERE (N - 1) = (
  SELECT COUNT(DISTINCT e2.SAL) 
  FROM EMPLOYEE e2 
  WHERE e2.department = e1.department AND e2.SAL > e1.SAL 
);

更好的解决方案是使用 DENSE_RANK() window 函数:

SELECT DISTINCT department, SAL
FROM ( 
  SELECT *, DENSE_RANK() OVER (PARTITION BY department ORDER BY SAL DESC) dr
  FROM EMPLOYEE 
)
WHERE dr = N;