这是leetcode的交换席位问题。
老师想给相邻的学生换座位。输入:
+---------+---------+
| id | student |
+---------+---------+
| 1 | Abbot |
| 2 | Doris |
| 3 | Emerson |
| 4 | Green |
| 5 | Jeames |
+---------+---------+
输出:
+---------+---------+
| id | student |
+---------+---------+
| 1 | Doris |
| 2 | Abbot |
| 3 | Green |
| 4 | Emerson |
| 5 | Jeames |
+---------+---------+
给定解决方案:
SELECT
(CASE
WHEN MOD(id, 2) != 0 AND counts != id THEN id + 1
WHEN MOD(id, 2) != 0 AND counts = id THEN id
ELSE id - 1
END) AS id,
student
FROM
seat,
(SELECT
COUNT(*) AS counts
FROM
seat) AS seat_counts
ORDER BY id ASC;
我的解决方案:
select
(Case
when mod(id,2) !=0 and id != count(*) then id + 1
when mod(id,2) !=0 and id = count(*) then id
else id - 1
end) as 'id',
student
from seat
order by id;
给定的解决方案效果很好,但我的只能得到一行输出。
我的输出:
+---------+---------+
| id | student |
+---------+---------+
| 2 | Abbot |
+---------+---------+
有人能解释一下我的解决方案和给定的解决方案有什么区别,为什么我的解决方案是错误的吗?谢谢。
1条答案
按热度按时间yyyllmsg1#
在查询中直接使用count()时,始终只有一行。另一种解决方案是通过使用子查询将count()用作整个查询的值。
尝试
和
观察差异。