我有一个课程,学生按年度入学,他们有出勤记录,我需要知道每年有多少人参加课程,实现这一目标需要多少SQL查询? / p>
预期产出:
YEAR COURSE ENROLED ATTENDED
---- ------ ------- --------
2017 IT 3 2
2018 IT 2 0
示例Oracle脚本:
--
DROP TABLE ATTENDANCE;
DROP TABLE ENROLMENT;
DROP TABLE STUDENT;
DROP TABLE COURSE;
--
CREATE TABLE COURSE (ID VARCHAR2(1), NAME VARCHAR2(20), PRIMARY KEY(ID));
CREATE TABLE STUDENT (ID VARCHAR2(1), NAME VARCHAR2(20), PRIMARY KEY(ID));
CREATE TABLE ENROLMENT (ID VARCHAR2(1), COURSE_ID VARCHAR2(1), STUDENT_ID VARCHAR2(1), YEAR VARCHAR2(4), PRIMARY KEY(COURSE_ID, STUDENT_ID, YEAR));
CREATE TABLE ATTENDANCE (ENROLMENT_ID VARCHAR2(1), PRIMARY KEY(ENROLMENT_ID));
--
INSERT INTO COURSE VALUES('1', 'IT');
INSERT INTO STUDENT VALUES('1', 'John');
INSERT INTO STUDENT VALUES('2', 'Mary');
INSERT INTO STUDENT VALUES('3', 'Peter');
INSERT INTO ENROLMENT VALUES('1', '1', '1', '2017');
INSERT INTO ENROLMENT VALUES('2', '1', '2', '2017');
INSERT INTO ENROLMENT VALUES('3', '1', '3', '2017');
INSERT INTO ENROLMENT VALUES('4', '1', '1', '2018');
INSERT INTO ENROLMENT VALUES('5', '1', '2', '2018');
INSERT INTO ATTENDANCE VALUES('1');
INSERT INTO ATTENDANCE VALUES('2');
COMMIT;
--
答案 0 :(得分:2)
怎么样:
select e.year, c.name,
count(distinct s.id) as enroled,
count(distinct a.enrolment_id) as attended
from enrolment e
join course c on e.course_id = c.id
left join student s on s.id = e.student_id
left join attendance a on a.enrolment_id = e.id
group by e.year, c.name
结果:
year name enroled attended
---- ---- ------- -----
2017 IT 3 2
2018 IT 2 0