Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3 超过 5 名学生的课 #4

Open
astak16 opened this issue Jan 3, 2022 · 0 comments
Open

3 超过 5 名学生的课 #4

astak16 opened this issue Jan 3, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Jan 3, 2022

题目

查出超过或等于 5 名学生的课(学生的课不被重复计算)

create table courses (
	student varchar(255),
	class varchar(255)
)

insert into courses values
('A', 'Math'),
('B', 'English'),
('C', 'Math'),
('D', 'Biology'),
('E', 'Math'),
('F', 'Computer'),
('G', 'Math'),
('H', 'Math'),
('I', 'Math');

SQL:方法一

select class from courses group by class having count(*) >= 5;

解析

学生的课不重复,所以按照 class 分组,在使用 having 筛选出大于等于 5 课的同学

SQL:方法二

select class from (
	select class, count(*) as num from courses group by class
) as c where num >= 5;

解析

  • 首先查出每门课的学生人数,使用 group by 分组
  • 把这次查询作为一个临时表
  • 再次对这张表进行查询,筛选条件是人数大于等于 5 人。
@astak16 astak16 added the 简单 label Jan 3, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant