gpt4 book ai didi

mysql - 使用 count 来计算值和空值

转载 作者:行者123 更新时间:2023-11-28 23:32:50 25 4
gpt4 key购买 nike

我有下面的查询

List the number of students graduated in 2009 by department. The results should show 0 for the departments that do not have any student graduated in 2009.

我在回答问题的第二部分时遇到了问题。截至目前,我的查询仅显示有学生毕业的部门。我不知道如何让表格显示没有任何学生毕业的部门。

我的查询看起来像这样

select d.name, count(s.major_id) as students from departments d
right join students s on s.major_id = d.id where extract( year from s.graduation_date ) = 2009
group by d.name

我的 table 是这样的

name    students
Math 2
Drama 1

如何让它显示其他部门没有学生毕业?

数据库是

create table departments (
id integer primary key,
name varchar(255)
);

insert into departments (id, name) values (10, 'Computer Science');
insert into departments (id, name) values (20, 'Math');
insert into departments (id, name) values (30, 'Drama');

create table faculty (
id integer primary key,
name varchar(255),
department_id integer references departments(id)
);

insert into faculty (id, name, department_id) values (1, 'Turing', 10);
insert into faculty (id, name, department_id) values (2, 'Newton', 20);
insert into faculty (id, name, department_id) values (3, 'Einstein', 20);
insert into faculty (id, name, department_id) values (4, 'Brando', 30);
insert into faculty (id, name, department_id) values (5, 'Joe', 30);
insert into faculty (id, name, department_id) values (6, 'Gray', 10);

create table students (
id integer primary key,
name varchar(255),
graduation_date date,
major_id integer references departments(id)
);

insert into students (id, name, graduation_date, major_id) values
(1, 'Joe', null, 10);
insert into students (id, name, graduation_date, major_id) values
(2, 'Amy', '2009-04-22', 20);
insert into students (id, name, graduation_date, major_id) values
(3, 'Max', null, 10);
insert into students (id, name, graduation_date, major_id) values
(4, 'Sue', '2009-01-10', 20);
insert into students (id, name, graduation_date, major_id) values
(5, 'Bob', '2009-03-05', 30);
insert into students (id, name, graduation_date, major_id) values
(6, 'Kim', null, 20);
insert into students (id, name, graduation_date, major_id) values
(7, 'Art', null, 30);
insert into students (id, name, graduation_date, major_id) values
(8, 'Pat', '2005-07-11', 20);
insert into students (id, name, graduation_date, major_id) values
(9, 'Lee', null, 10);

最佳答案

尝试使用 LEFT JOIN 而不是 RIGHT JOIN:

select d.name, count(s.major_id) as students 
from departments d
left join students s on s.major_id = d.id and
extract( year from s.graduation_date ) = 2009
group by d.name

注意 extract( year from s.graduation_date ) = 2009 谓词应该放在 ON 子句中,否则 LEFT JOIN 变成一个内部连接

输出:

 name            | students
=================+============
Computer Science | 0
Drama | 1
Math | 2

关于mysql - 使用 count 来计算值和空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36884640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com