如何选择最少的学生找到课程名称

时间:2019-04-19 22:20:51

标签: mysql

有没有办法找到最少被选学生的课程名称?

我非常感谢您的帮助。

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       |
+---------+------------+

3 个答案:

答案 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)

您需要做的是:

  • 在选择字段中,使用“计数”功能对学生人数进行计数
  • 由于您需要按类别对它们进行分组,因此请在类别列中使用“ group by”语句
  • 您需要的学生人数较少的班级,因此请对所有结果进行“排序依据”排序

实际查询将更多地像这样:

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 |
+----------+-----+