[Leetcode] 1280. Students and Examinations

2025. 9. 14. 12:46·SQL

<문제>

Write a solution to find the number of times each student attended each exam.
Return the result table ordered by student_id and subject_name.

학생이 본 시험 횟수를 계산하는 문제.

 

Explanation: 
The result table should contain all students and all subjects.
Alice attended the Math exam 3 times, the Physics exam 2 times, and the Programming exam 1 time.
Bob attended the Math exam 1 time, the Programming exam 1 time, and did not attend the Physics exam.
Alex did not attend any exams.
John attended the Math exam 1 time, the Physics exam 1 time, and the Programming exam 1 time.

 

→ 모든 학생과 모든 과목이 포함된 집계를 해야함.

 

<테이블 예시>

# Students 테이블
+------------+--------------+
| 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              |
+------------+--------------+--------------+----------------+

 

처음 시도.

left join , group by 사용 

SELECT 
    s.student_id, 
    s.student_name, 
    e.subject_name, 
    COUNT(e.exam_id) AS attended_exams
FROM students s
LEFT JOIN examinations e
    ON s.student_id = e.student_id
GROUP BY 
    s.student_id, 
    s.student_name, 
    e.subject_name
ORDER BY 
    s.student_id, 
    e.subject_name;

 

틀렸던 이유:

subject 테이블에 따로 아이디가 없어 맵핑 하지 않음.

Examination테이블에 학생이 치루지 않은 과목의 경우 집계되지 않음.

 

해결:

Cross Join를 사용해 Student x Subjects 즉, 모든학생과 모든과목 조합생성한 뒤, 시험 본 횟수 집계

 

SELECT 
    s.student_id,
    s.student_name,
    sub.subject_name,
    COUNT(e.student_id) AS attended_exams
FROM Students s
CROSS JOIN Subjects sub
LEFT JOIN Examinations e
    ON s.student_id = e.student_id
   AND sub.subject_name = e.subject_name
GROUP BY 
    s.student_id,
    s.student_name,
    sub.subject_name
ORDER BY 
    s.student_id,
    sub.subject_name;

 

'SQL' 카테고리의 다른 글

[HackerRank] Weather Observation Station20: Median(중앙값) 구하기  (1) 2025.03.23
[HackerRank] Occupations 직업별 피벗 테이블 만들기  (0) 2025.03.19
[HackerRank] The PADS 안됐던 이유 정리  (0) 2025.03.14
[HackerRank SQL] Draw The Triangle 별 삼각형 그리  (0) 2025.03.06
'SQL' 카테고리의 다른 글
  • [HackerRank] Weather Observation Station20: Median(중앙값) 구하기
  • [HackerRank] Occupations 직업별 피벗 테이블 만들기
  • [HackerRank] The PADS 안됐던 이유 정리
  • [HackerRank SQL] Draw The Triangle 별 삼각형 그리
데이터먼지
데이터먼지
데이터분석 및 AI Agent 개발하고 있습니다 :)
  • 데이터먼지
    먼지's Data Analysis
    데이터먼지
  • 전체
    오늘
    어제
    • 분류 전체보기 (46)
      • AI agent (3)
      • 데이터분석 (24)
        • 데이터분석 (4)
        • 데이터 전처리 (10)
        • 데이터시각화 (3)
        • 시계열분석 (6)
        • 환경세팅 (1)
      • SQL (7)
      • 개발&분석 경험 (2)
      • 알고리즘 (3)
      • OS (1)
      • 수학 (4)
        • 선형대수 (2)
        • 확률&통계 (2)
      • 맛집 (2)
        • 이수&사당 (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    리눅스개념
    확률
    플로틀리
    SQL
    Python
    timeseries decomposition
    seaborn # kdeplot # 데이터분석
    시계열
    pandas
    짧은 시계열 # 금융시계열
    stl
    오제이튜브
    이수역 양식집
    시계열모듈
    np.split
    데이터분석
    시계열데이터셋
    loess
    시계열시각화
    adf_test
    음수값 #전처리 #선형보간 #pandas #데이터 #데이터분석
    시계열분해
    시간형식변환
    시계열 #reindex #인덱스 확장 #datetime index #index extention # 데이터전처리
    파이프라인전처리
    pandas # 월말 날짜 # 마지막 주 # 날짜계산 # 시계열 # 마지막 주 금요일
    시간형식
    크롤링자동화
    응용이 보이는 선형대수
    빈 데이터프레임 #pandas #데이터전처리
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
데이터먼지
[Leetcode] 1280. Students and Examinations
상단으로

티스토리툴바