๐ป ๋ฌธ์ ์ฃผ์ : Students and Examinations - LeetCode
Students and Examinations - LeetCode
Can you solve this real interview question? Students and Examinations - Table: Students +---------------+---------+ | Column Name | Type | +---------------+---------+ | student_id | int | | student_name | varchar | +---------------+---------+ student_id is
leetcode.com
๐ป ๋ฌธ์
Write a solution to find the number of times each student attended each exam. Return the result table ordered by student_id an subject_name.
- ํ์๋ณ๋ก ์ฐธ์ํ ์ํ ํ์๋ฅผ ๊ตฌํ์์ค. student_id์ subject_name์ ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์ ์ ๋ ฌํ์ฌ ์ถ๋ ฅํ์์ค.
๐ป ์ฝ๋ ๋ฐ ํ์ด
select s.student_id, s.student_name, sub.subject_name, count(e.subject_name) 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
1๏ธโฃ Cross Join
ํฌ๋ก์ค ์กฐ์ธ์ด๋ ํ ์ด๋ธ A, B ๋ด ๋ชจ๋ ํ์ ๋งค์นญ์ํค๋ ์กฐ์ธ์ผ๋ก, ๊ฒฐ๊ณผ๋ ๋ ํ ์ด๋ธ ๊ฐ ํ ๊ฐ์๋ฅผ ๊ณฑํ ์๋งํผ ํ์ ๊ฐ์ง๊ฒ ๋๋ค.

์ ์์ ์ด๋ฏธ์ง์ ๊ฒฝ์ฐ, (1, 2, 3)ํ์ ๊ฐ์ง๊ณ ์๋ ํ ์ด๋ธ A์ (a, b, c)ํ์ ๊ฐ์ง๊ณ ์๋ B๋ฅผ ํฌ๋ก์ค ์กฐ์ธํ๋ฉด 3(ํ ์ด๋ธ A ํ) x 3(ํ ์ด๋ธ B) = 9, ์ด 9๊ฐ์ ํ์ ๊ฐ์ง๊ฒ ๋๋ค.
ํฌ๋ก์ค ์กฐ์ธ ํ์ฉ ์์๋ ์ด์ฐจํผ ๋ชจ๋ ํ์ ๋ค ๋งค์นญ์ํค๊ธฐ ๋๋ฌธ์ on์ด๋ using์ ํ์ฉํด ํน์ ์กฐ๊ฑด์ด ๋ง๋ ํ๋ผ๋ฆฌ ์กฐ์ธ์ํฌ ํ์๊ฐ ์๋ค. ์ ๋ฌธ์ ํ์ด ๋ํ ํฌ๋ก์ค ์กฐ์ธ ์ on ๋ฑ์ ์ฌ์ฉํ์ง ์์์์ ํ์ธํ ์ ์๋ค.
'SQL > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode][SQL50] #14. Confirmation Rate (0) | 2023.11.13 |
---|---|
[LeetCode][SQL50] #13. Managers with at Least 5 Direct Reports (0) | 2023.11.09 |
[LeetCode][SQL50] #11. Employee Bonus (0) | 2023.11.08 |
[LeetCode][SQL50] #10. Average Time of Process per Machine (0) | 2023.11.08 |
[LeetCode][SQL50] #9. Rising Temperature (0) | 2023.11.08 |