有没有办法找到最少被选学生的课程名称?
我非常感谢您的帮助。
SQL模式:
normal
表格:
Create table If Not Exists courses (student varchar(255), class varchar(255))
Truncate table courses
insert into courses (student, class) values ('A', 'Math')
insert into courses (student, class) values ('B', 'English')
insert into courses (student, class) values ('C', 'Math')
insert into courses (student, class) values ('D', 'Biology')
insert into courses (student, class) values ('E', 'Math')
insert into courses (student, class) values ('F', 'Computer')
insert into courses (student, class) values ('G', 'Math')
insert into courses (student, class) values ('H', 'Math')
insert into courses (student, class) values ('I', 'Math')
应输出:
+---------+------------+
| student | class |
+---------+------------+
| A | Math |
| B | English |
| C | Math |
| D | Biology |
| E | Math |
| F | Computer |
| G | Math |
| H | Math |
| I | Math |
+---------+------------+
答案 0 :(得分:4)
您可以使用HAVING
子句来完成此操作:
SELECT
class
FROM
courses
GROUP BY
class
HAVING
COUNT(*)=(
SELECT
COUNT(*)
FROM
courses
GROUP BY
class
ORDER BY
COUNT(*) ASC
LIMIT 1
)
希望这会有所帮助,
答案 1 :(得分:1)
您需要做的是:
实际查询将更多地像这样:
select count(student) as cant_student, class
from #courses
group by class
order by cant_student
我使用SQL Server完成此操作,但在MySQL中却是相同的
答案 2 :(得分:0)
您可以构建如下查询:
结果查询如下:
SELECT
class,
COUNT(*) as num
FROM
courses
GROUP BY
class
HAVING
num = (
SELECT
num
FROM
(
SELECT
class,
COUNT(*) as num
FROM
courses
GROUP BY
class
ORDER BY
num
) c
LIMIT 1
);
结果将是:
+----------+-----+
| class | num |
+----------+-----+
| Biology | 1 |
| Computer | 1 |
| English | 1 |
+----------+-----+