๐ป ๋ฌธ์ ์ฃผ์ : https://leetcode.com/problems/find-followers-count/description/?envType=study-plan-v2&envId=top-sql-50
Find Followers Count - LeetCode
Can you solve this real interview question? Find Followers Count - Table: Followers +-------------+------+ | Column Name | Type | +-------------+------+ | user_id | int | | follower_id | int | +-------------+------+ (user_id, follower_id) is the primary ke
leetcode.com
๐ป ๋ฌธ์
Write a solution that will, for each, return the number of followers. Return the result table ordered by user_id in ascending order.
๐ป ์ฝ๋ ๋ฏธ๋ฆฌ๋ณด๊ธฐ
select user_id, count(follower_id) as followers_count
from Followers
group by user_id
order by user_id
๐ป ๋ฌธ์ ํ์ด
์ด๋ฒ ๋ฌธ์ ๋ ๋ฌธ์ ๋ฅผ ๊ทธ๋๋ก ์ง์ญํด ์ฟผ๋ฆฌ๋ก ์ฎ๊ธฐ๋ฉด ๋๋ค.
1๏ธโฃ return the number of followers → ํ๋ก์๋ค(follower_id)์ '์'๋ฅผ ์ถ์ถํ๋ผ
2๏ธโฃ ordered by user_id in ascending order → user_id๋ฅผ ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์ ์ ๋ ฌํ๋ผ
์ ๋ด์ฉ์ ๊ทธ๋๋ก ์ฟผ๋ฆฌ๋ก ์ฎ๊ฒจ๋ณด์. ์ฐ์ 1๏ธโฃ์ ์ฟผ๋ฆฌ๋ก ์ฎ๊ธฐ๋ฉด ์๋์ ๊ฐ๋ค. user_id๋ณ๋ก ํ๋ก์ ์๊ฐ ์ผ๋ง ๋๋์ง๋ฅผ ๊ตฌํ๋ ๊ฒ์ด๋ select ์ ์ ์ฐ๋ฆฌ๊ฐ ์ํ๋ ๊ฐ์ ์ถ์ถํ๊ณ ์ ์ปฌ๋ผ๋ช ์ ์ ์ผ๋ฉด ๋๋ค.
-- 1๏ธโฃ return the number of followers
select user_id, count(follower_id) as followers_count
from Followers
๊ทธ๋ฆฌ๊ณ ์ด์ ์ฝ๋์์ ํ ์ฐจ๋ก ์ธ๊ธํ๋ฏ, count() ํจ์๋ฅผ ์ฐ๊ธฐ ์ํด์๋ ์ปฌ๋ผ์ ์งํฉ์ผ๋ก ๋ฌถ์ด์ค ํ์๊ฐ ์๋ค. ์ฐ๋ฆฌ๊ฐ ๊ตฌํ๊ณ ์ ํ๋ ๊ฒ์ 'user_id'๋ณ๋ก 'follower_id'์ด๊ธฐ ๋๋ฌธ์ user_id๋ฅผ group by๋ก ๋ฌถ์ด์ค์ผ ํ๋ค.
select user_id, count(follower_id) as followers_count
from Followers
group by user_id
๋ง์ง๋ง์ผ๋ก ์ ๋ ฌ๋ง ์ ํด์ฃผ๋ฉด ๋๋๋ค. ๋ฌธ์ ์์๋ user_id๋ฅผ ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์ ์ ๋ ฌํ๊ธฐ๋ฅผ ์ํ๋ค๊ณ ํ๋ ๊ทธ๋๋ก ์ฎ๊ฒจ์ฃผ๋ฉด ๋๋ค. ์ด๋ order by์ default๋ ์ค๋ฆ์ฐจ์(asc)์ด๊ธฐ ๋๋ฌธ์ ๋ณ๋๋ก ์ปฌ๋ผ ๋ค์ asc๋ฅผ ์ ์ง ์์๋ ๋๋ค.
select user_id, count(follower_id) as followers_count
from Followers
group by user_id
-- 2๏ธโฃ ordered by user_id in ascending order
order by user_id
'SQL > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[SQL50] #29. Customers Who Bought All Products (1) | 2024.01.09 |
---|---|
[SQL50] #28. Biggest Single Number (1) | 2024.01.07 |
[SQL50] #26. Classes More Than 5 Students (1) | 2024.01.05 |
[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 |