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

35 统计各专业学生人数 #42

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

35 统计各专业学生人数 #42

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

Comments

@astak16
Copy link
Owner

astak16 commented Jan 31, 2022

题目

查询每个专业的学生人数(没有学生的专业也需要列出),将查询结果按照学生人数降序排列,如果两个或者两个以上的专业有相同的学生人数,按照专业名的字典从小到大排列

create table student(
	student_id int,
	student_name varchar(255),
	gender varchar(255),
	dept_id int
);

insert into student values
(1, 'Jack', 'M', 1),
(2, 'Jane', 'F', 1),
(3, 'Mark', 'M', 2);

create table department(
	dept_id int,
	dept_name varchar(255)
);

insert into department values
(1, 'Engineering'),
(2, 'Science'),
(3, 'Law');

SQL

SELECT
	dept_name,
	count( student_id ) AS student_number 
FROM
	department
	LEFT JOIN student ON department.dept_id = student.dept_id 
GROUP BY
	dept_name 
ORDER BY
	dept_name DESC

解析

这题有两个要点:

  1. 哪张表连哪张表
  2. count 处理 null 时的问题

第一点,因为现在要计算每个专业的人数,如果是 student 左连 department 就会忽略掉没有人的专业,造成最后专业缺失,所以要用 department 左连 student

第二点, count(*) 计算的是总行数,不会忽略 null ,但是这里有些专业没有人,计算出来应该是 0 ,所以应该使用 count(student_id)

@astak16 astak16 added the 中等 label Jan 31, 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