SQL中如何输出“NULL”而不是“没有要显示的结果”当没有值可导出时
现在使用MySQL v8.0。
问题是:
编写一个 SQL 查询来报告来自第二高薪水的 id 和薪水 员工表。如果没有第二高的工资,则查询应该 报告为空。
我的虚拟数据是:
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,但没有成功。我想这是因为输出实际上不是空的而是空的。
先感谢您。
Using MySQL v8.0 right now.
The question is:
Write an SQL query to report the id and the salary of the second highest salary from the
Employee table. If there is no second highest salary, the query should
report null.
My dummy data is:
Create table If Not Exists Employee (id int, salary int);
insert into Employee (id, salary) values
(1, 100);
My ideal output is like this:
+------+--------+
| id | salary |
+------+--------+
| NULL | NULL |
+------+--------+
I used DENSE_RANK as a more straightforward way for me to solve this question:
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
But I have a problem exporting NULL when there's no second highest salary. I tried IFNULL, but it didn't work. I guess it's because the output is not actually null but just empty.
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=31f5afb0e7e5dce9c2c128ccc49a6f42
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=31f5afb0e7e5dce9c2c128ccc49a6f42
在我看来,仅使您的查询成为子查询并从单行生成子查询进行左连接似乎是最简单的方法:(
我通常更喜欢子查询而不是仅使用一次的 cte;我发现这很混乱。)
Just making your query a subquery and left joining from a single-row producing subquery seems to me the simplest approach:
(I usually prefer a subquery to a cte that's only used once; I find that obfuscatory.)