๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
SQL/LeetCode

[LeetCode][SQL50] #12. Students and Examinations

by ์ด๋ฎด 2023. 11. 9.
728x90

๐Ÿ’ป ๋ฌธ์ œ ์ฃผ์†Œ : 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 ๋“ฑ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•˜์Œ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•

'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