596. Classes More Than 5 Students

  1. Classes More Than 5 Students
    There is a table courses with columns: student and class
    Please list out all classes which have more than or equal to 5 students.
    For example, the table:
    +———+————+
    | student | class |
    +———+————+
    | A | Math |
    | B | English |
    | C | Math |
    | D | Biology |
    | E | Math |
    | F | Computer |
    | G | Math |
    | H | Math |
    | I | Math |
    +———+————+
    Should output:
    +———+
    | class |
    +———+
    | Math |
    +———+

* Note:
The students should not be counted duplicate in each course.*
Solution

Approach1: Using GROUP BY clause and sub-query [Accepted]

To get the student number in each class. We can use GROUP BY and COUNT, which is very popular used to statistic bases on some character in a table.

SELECT
class, COUNT(DISTINCT student)
FROM
courses
GROUP BY class
;
Note: We use DISTINCT here since the student name may duplicated in a class as it is mentioned int he problem description.

classCOUNT(student)
Biology1
Computer1
English1
Math6

To continue, we can filter the classes by taking the above query as a sub-query.

SELECT
class
FROM
(SELECT
class, COUNT(DISTINCT student) AS num
FROM
courses
GROUP BY class) AS temp_table
WHERE
num >= 5
;

Note: Make an alias of COUNT(student) (‘num’ in this case) so that you can use in the WHERE clause because it cannot be used directly over there.
Approach: Using GROUP BY and HAVING condition [Accepted]

Algorithm

Using sub-query is one way to add some condition to a GROUP BY clause, however, using HAVING is another simpler and natural approach. So we can rewrite the above solution as below.

SELECT
class
FROM
courses
GROUP BY class
HAVING COUNT(DISTINCT student) >= 5

Count(0), Count(1), Count() 用法与比较*

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值