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

[SQL50] #27. Find Followers Count

by ์ด๋ฎด 2024. 1. 6.
728x90

๐Ÿ’ป ๋ฌธ์ œ ์ฃผ์†Œ : 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.

Input๊ณผ Output ์˜ˆ์‹œ

 

๐Ÿ’ป ์ฝ”๋“œ ๋ฏธ๋ฆฌ๋ณด๊ธฐ

๋”๋ณด๊ธฐ
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

 

728x90
๋ฐ˜์‘ํ˜•

'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