2

有没有办法选择 group by 子句中指定的列以外的列?假设我有以下架构:

Student(id, name, age), Course(id, name, credit), Enrollment(student_id, course_id, Grade)

我想为每门课程查询以下内容:课程名称,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;
4

2 回答 2

3

您可能想要复制此 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');

现在,您只需查询“enrollment”表就可以得到每门课程的学生人数。

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

剩下的就是获取相应的课程名称。为此,您只需将表“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
于 2013-04-11T19:53:46.720 回答
2

不,你不能。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是独一无二的,所以不会改变结果。

于 2013-04-11T19:36:32.887 回答