现在使用MySQL v8.0。
问题是:
编写一个SQL查询,从Employee表中报告第二高薪资的id和薪资。如果没有第二个最高薪资,则查询应报告null。
我的虚拟数据是:
Create table If Not Exists Employee (id int, salary int);
insert into Employee (id, salary) values
(1, 100);我的理想输出如下:
+------+--------+
| id | salary |
+------+--------+
| NULL | NULL |
+------+--------+我使用DENSE_RANK作为解决这个问题的更直接的方法:
WITH sub AS (SELECT id,
salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS num
FROM Employee )
SELECT id, salary
FROM sub
WHERE num = 2但是当没有第二高工资的时候,我很难输出NULL。我试过IFNULL,但没成功。我想这是因为输出实际上不是空的,而是空的。
提前谢谢你。
发布于 2022-03-03 05:43:34
WITH sub AS (
SELECT id,
salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS num
FROM Employee
)
SELECT id, salary
FROM sub
WHERE num = 2
UNION ALL
SELECT NULL, NULL
WHERE 0 = ( SELECT COUNT(*)
FROM sub
WHERE num = 2 );https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=31f5afb0e7e5dce9c2c128ccc49a6f42
发布于 2022-03-04 00:26:45
在我看来,仅仅将查询作为子查询并从单行生成子查询中退出连接,似乎是最简单的方法:
select id, salary
from (select null) at_least_one_row
left join (
select id, salary
from (
select id, salary, dense_rank() over (order by salary desc) as num
from Employee
) ranked_employees
where num = 2
) second_highest_salary on true(与只使用一次的cte相比,我通常更喜欢子查询;我发现这很模糊。)
https://stackoverflow.com/questions/71331658
复制相似问题