有没有办法选择group by子句中指定的列以外的列? 假设我有以下架构:
学生(身份证,姓名,年龄),课程(身份证,姓名,学分),报名(student_id,course_id,年级)
我想查询以下每门课程:课程名称,student_count。
我提出了解决方法,但我想知道是否有更简洁的方法来做到这一点:
SELECT MAX(c.name), COUNT(distinct e.student_id)
FROM Enrollment e
INNER JOIN Course c ON c.id = e.course_id
GROUP BY e.course_id;
答案 0 :(得分:2)
您可能希望复制此DDL,将其调整为与您的架构相匹配,然后将其粘贴到您的问题中。
create table Student(
student_id integer primary key,
student_name varchar(35) not null,
age int not null default 20
);
create table Course(
course_id integer primary key,
course_name varchar(35) not null,
credit integer not null default 3
);
create table Enrollment(
student_id integer not null references Student (student_id),
course_id integer not null references Course (course_id),
primary key (student_id, course_id),
grade char(1) not null
);
insert into student values
(1, 'a', 20),
(2, 'b', 20),
(3, 'c', 20);
insert into course values
(1, 'course 1', 3),
(2, 'course 2', 3),
(3, 'course 3', 3);
insert into enrollment values
(1, 1, 'b'),
(2, 1, 'b'),
(3, 1, 'b'),
(1, 2, 'b'),
(2, 2, 'b'),
(3, 3, 'b');
现在,您只需查询“注册”表,即可获得每门课程注册的学生人数。
select course_id, count(student_id) num_students
from enrollment
group by course_id
order by course_id;
course_id num_students
--
1 3
2 2
3 1
剩下的就是获得相应的课程名称。为此,您只需将表格“课程”与我们刚写的查询一起加入。
select course.course_name, course_enrollment.num_students
from course
inner join (select course_id, count(student_id) num_students
from enrollment
group by course_id) course_enrollment
on course.course_id = course_enrollment.course_id;
course_name num_students
--
course 1 3
course 3 1
course 2 2
答案 1 :(得分:1)
GROUP BY
扩展c.name
:
SELECT MAX(c.name), COUNT(distinct e.student_id)
FROM Enrollment e
INNER JOIN Course c ON c.id = e.course_id
GROUP BY e.course_id, c.name
由于e.course_id
是唯一的,因此不会更改结果。