[TIL]_2025.03.18 본캠프 30일차 (3): 코드카타 SQL

JIYUU·2025년 3월 19일

87번. [Employee Bonus]
(https://leetcode.com/problems/employee-bonus/)

select 
	e.name, b.bonus
from 
	Employee e
left join 
	Bonus b
on 
	e.empId = b.empId
where 
	b.Bonus is null or b.Bonus < 1000

88번. Students and Examinations

select 
    st.student_id,
    st.student_name,
    sb.subject_name, 
    count(e.student_id) as attended_exams
from students st
join subjects sb
left join examinations e
on st.student_id = e.student_id and sb.subject_name = e.subject_name
group by 1,3
order by 1,3

구글링으로 겨우겨우 푼 문제.
join이 공통 컬럼 없이도 그냥 된다는 사실을 처음 알았다.
students와 subjects를 join으로 결합하고,
시험을 안 본 학생 즉, examination에 없는 학생도 조회해야 하기 때문에 그것을 left join으로 결합.
그리고 공통 컬럼에 어떤 학생이 어떤 시험을 봤는지 확인해야하기 때문에 on st.student_id ~ and sb.subject_name ~.
on에 공통 컬럼을 and로 묶을 수 있는 것도 겨우 기억났다.
그리고 subject_name 기준으로 묶어서 해당 시험을 본 학생이 있는지 카운트 해야 하기 때문에 count(student_id)를 해준다.

0개의 댓글