문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
Table: Students
| Column Name | Type |
|---|---|
| student_id | int |
| student_name | varchar |
student_id는 이 테이블의 기본 키이다.
테이블의 각 행은 학교의 학생 이름과 ID를 포함한다.
Table: Subjects
| Column Name | Type |
|---|---|
| subject_name | varchar |
subject_name은 이 테이블의 기본 키이다.
테이블의 각 행은 학교의 과목의 이름을 포함한다.
Table: Examinations
| Column Name | Type |
|---|---|
| student_id | int |
| subject_name | varchar |
이 테이블에 기본 키는 없다. 중복을 포함할 수도 있다.
Students 테이블에서 각 학생은 Subjects 테이블에서 모든 과목을 수강한다.
이 테이블의 각 행은 student_id를 가진 학생이 subject_name의 시험에 응시한 것을 나타낸다.
각 학생이 각각의 시험에 응시한 횟수를 구하는 방법을 작성해라.
Input:
Students table:
| student_id | student_name |
|---|---|
| 1 | Alice |
| 2 | Bob |
| 13 | John |
| 6 | Alex |
Subjects table:
| subject_name |
|---|
| Math |
| Physics |
| Programming |
Examinations table:
| student_id | subject_name |
|---|---|
| 1 | Math |
| 1 | Physics |
| 1 | Programming |
| 2 | Programming |
| 1 | Physics |
| 1 | Math |
| 13 | Math |
| 13 | Programming |
| 13 | Physics |
| 2 | Math |
| 1 | Math |
Output:
| student_id | student_name | subject_name | attended_exams |
|---|---|---|---|
| 1 | Alice | Math | 3 |
| 1 | Alice | Physics | 2 |
| 1 | Alice | Programming | 1 |
| 2 | Bob | Math | 1 |
| 2 | Bob | Physics | 0 |
| 2 | Bob | Programming | 1 |
| 6 | Alex | Math | 0 |
| 6 | Alex | Physics | 0 |
| 6 | Alex | Programming | 0 |
| 13 | John | Math | 1 |
| 13 | John | Physics | 1 |
| 13 | John | Programming | 1 |
Explanation:
결과 테이블은 모든 학생과 모든 과목을 포함해야한다.
Alice는 Math에 3번, Physics에 2번, Programming에 1번 응시했다.
Bob는 Math에 1번, Programming에 1번 응시했고, Physics는 응시하지 않았다.
Alex는 어떤 시험도 응시하지 않았다.
John은 Math에 1번, Physics에 1번, Programming에 1번 응시했다.
-- Write your PostgreSQL query statement below
select
A.student_id,
A.student_name,
B.subject_name,
count(C.student_id) as attended_exams
from Students A
cross join Subjects B
left outer join Examinations C on A.student_id = C.student_id and B.subject_name = C.subject_name
group by A.student_id, A.student_name, B.subject_name
order by A.student_id, A.student_name, B.subject_name