๐ป ๋ฌธ์ ์ฃผ์ : https://leetcode.com/problems/classes-more-than-5-students/?envType=study-plan-v2&envId=top-sql-50
Classes More Than 5 Students - LeetCode
Can you solve this real interview question? Classes More Than 5 Students - Table: Courses +-------------+---------+ | Column Name | Type | +-------------+---------+ | student | varchar | | class | varchar | +-------------+---------+ (student, class) is the
leetcode.com
๐ป ๋ฌธ์
Write a solution to find all the classes that have at least five students. Return the result table in any order.

๐ป ์ฝ๋ ๋ฏธ๋ฆฌ๋ณด๊ธฐ
select class from Courses group by class having count(class) >= 5
๐ป ๋ฌธ์ ํ์ด
์ด๋ฒ ๋ฌธ์ ๋ ํฌ๊ฒ ์ด๋ ค์ธ ๊ฒ์ด ์์์ผ๋ Solution์ ํ ๊ฐ์ง ๋์ ๋๋ ์ง๋ฌธ์ด ์์ด์ ํฐ์คํ ๋ฆฌ์๋ ๋ฃ์ด๋ณด๊ณ ์ ํ๋ค.
Why we can't use 'where' in this?
๋ผ๋ ์ง๋ฌธ์ผ๋ก, ์ฟผ๋ฆฌ์ where ์กฐ๊ฑด์ด ์๋ having ์ ์ ๋ฃ๋ ๊ฒ์ ๋ํ ๋ฌธ์์๋ค. ์ด ๋ถ๋ถ์ ๋ํ ๋ต์ ํ๊ธฐ ์ํด ๋ฌธ์ ๋ฅผ ๋ค์ ํ ๋ฒ ํ์ธํด๋ณด์.
1๏ธโฃ To find all the classes that have at least five students
์ต์ 5๋ช ์ ์๊ฐ์์ด ์๋ ์์ ์ ์ฐพ๋ ๊ฒ์ด ์ด๋ฒ ๋ฌธ์ ์ ์กฐ๊ฑด์ด๋ค. Courses ํ ์ด๋ธ์๋ Math, English ๋ฑ ๋ง์ ํ ์ด๋ธ์ด ์๋ค. ์ด ํ ์ด๋ธ๋ณ๋ก ๋ฐ์ดํฐ๋ฅผ ๋ชจ์ผ๊ธฐ ์ํด์๋ group by๊ฐ ์ฐ์ฌ์ผ ํ๋ค๋ ๊ฒ์ ๋ค๋ค ๋์น์ฑ์ ๊ฒ์ด๋ค.
๋ค๋ง ์ where์ด ์๋ having์ธ๊ฐ? ๋ผ๋ ๊ฒ์ด ๊ทธ๋ค์ ์ง๋ฌธ์ธ๋ฐ, ์ด๋ group by ๋๋ฌธ์ด๋ค.
์ด๋ฏธ Courses ํ ์ด๋ธ์ 'ํ ์ด๋ธ๋ณ๋ก'๋ผ๋ ์กฐ๊ฑด ๋๋ฌธ์ ์ด๋ฏธ ๋ ์ฝ๋๋ค์ด class๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ฌถ์ฌ ์๋ ์ํ์ด๋ค. ๊ทธ๋ฆฌ๊ณ class ๋ณ๋ก ์๊ฐ์์ ๊ตฌํ๋ค๋ ๊ฒ์, ๋ ์ฝ๋ ํ๋ํ๋์ ์กฐ๊ฑด์ ๊ฑด๋ค๋ ๋ป์ด ์๋๋ผ class๋ก ๋ฌถ์ธ '์งํฉ'์ ์กฐ๊ฑด์ ๊ฑด๋ค๋ ๋ป์ด๋ค.
ํ ๋ฒ where ์ ๋ก ํด๋์ค ์๊ฐ์์ด 5๋ช ์ด์์ด๋ผ๋ ์กฐ๊ฑด์ ๊ฑธ์ด๋ณด์.
select class from Courses where count(class) >= 5
์ ์ฟผ๋ฆฌ๋ฅผ ์คํํ๋ฉด Invalid use of group function์ด๋ผ๋ ์๋ฌ๊ฐ ๋ฐ์ํ๋ค. ๊ทธ๋๋ก ํด์ํ๋ฉด group ๊ธฐ๋ฅ ์ฌ์ฉ ์์ฒด๊ฐ ์ ํจํ์ง ์๋ค๋ ๊ฒ์ด๋ค. where ์ ์์ ์๊ฐ์ ์ธ์์ ์ธ๊ธฐ ์ํด count() ํจ์๋ฅผ ์ผ๋๋ฐ ์ ์ด์ class ์ปฌ๋ผ ์์ฒด๊ฐ ํ์ฌ ๋ฌถ์ฌ ์๋ ์งํฉ ์ํ๊ฐ ์๋๋ ์ ์ ์๋ count๋ ์๊ธฐ ๋๋ฌธ์ group function์ด ์ ํจํ์ง ์๋ค๋ ์๋ฌ๊ฐ ๋ฐ์ํ ๊ฒ์ด๋ค.
'SQL > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[SQL50] #28. Biggest Single Number (1) | 2024.01.07 |
---|---|
[SQL50] #27. Find Followers Count (2) | 2024.01.06 |
[LeetCode][SQL50] #25. Product Sales Analysis III (1) | 2024.01.04 |
[LeetCode][SQL50] #24. User Activity for the Past 30 Days I (1) | 2024.01.04 |
[LeetCode][SQL50] #23. Number of Unique Subjects Taught by Each Teacher (1) | 2024.01.03 |