案例陈述问题(按课程数组织部门)

r8uurelv  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(279)

从本质上讲,我试图做一个案例陈述,计算计算机科学系、生物系的课程数,以及其他所有课程的总数。
应该是这样的:

以下是我的查询实际显示的内容:

请让我知道如果有什么不合理或你需要更多的信息。谢谢!
这是表架构和数据:

create table course (
    course_id varchar(8),
    title varchar(50), 
    dept_name varchar(20),
    credits numeric(2,0) check (credits > 0),
    primary key (course_id)
);

insert into course values ('BIO-101', 'Intro. to Biology', 'Biology', '4');
insert into course values ('BIO-301', 'Genetics', 'Biology', '4');
insert into course values ('BIO-399', 'Computational Biology', 'Biology', '3');
insert into course values ('CS-101', 'Intro. to Computer Science', 'Comp. Sci.', '4');
insert into course values ('CS-190', 'Game Design', 'Comp. Sci.', '4');
insert into course values ('CS-315', 'Robotics', 'Comp. Sci.', '3');
insert into course values ('CS-319', 'Image Processing', 'Comp. Sci.', '3');
insert into course values ('CS-347', 'Database System Concepts', 'Comp. Sci.', '3');
insert into course values ('EE-181', 'Intro. to Digital Systems', 'Elec. Eng.', '3');
insert into course values ('FIN-201', 'Investment Banking', 'Finance', '3');
insert into course values ('HIS-351', 'World History', 'History', '3');
insert into course values ('MU-199', 'Music Video Production', 'Music', '3');
insert into course values ('PHY-101', 'Physical Principles', 'Physics', '4');

我现在的问题是:

select
    dept_name,
    case
        when dept_name = 'Comp. Sci.' then count(course_id)
        when dept_name = 'Biology' then count(course_id)
        else count(course_id)
    end as 'Courses'
from
    course
group by
    dept_name;
hgqdbh6s

hgqdbh6s1#

此查询的一种方法是创建 new_dept_name “加入”列需要将进入标签的部门名称 Other ,那么 group by 这个新的栏目,终于用上了标准 count() 在这些组上:

SELECT
    CASE
        WHEN dept_name = "Biology" THEN "Biology"
        WHEN dept_name = "Comp. Sci." THEN "Comp. Sci."
        ELSE "Other"
    END AS new_dept_name,
    count(course_id) AS numCourses
FROM
    course
GROUP BY
    new_dept_name

您可以在此处查看一个在线示例:
小提琴

相关问题