有没有一种方法可以选择 group by 子句中指定的列以外的列? 假设我有以下架构:
学生(id、姓名、年龄)、类(class)(id、姓名、学分)、入学情况(student_id、course_id、年级)
我想查询每门类(class)的以下信息:类(class)名称、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;
最佳答案
您可能需要复制此 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');
现在,您只需查询“注册”表即可获取每门类(class)注册的学生人数。
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
剩下的就是获取相应的类(class)名称。为此,您只需将表“Course”与我们刚刚编写的查询连接起来即可。
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
关于mysql - 选择 GROUP BY 子句中指定的列以外的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15957314/