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

[LeetCode][SQL50] #24. User Activity for the Past 30 Days I

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

๐Ÿ’ป ๋ฌธ์ œ ์ฃผ์†Œ : User Activity for the Past 30 Days I - LeetCode

 

User Activity for the Past 30 Days I - LeetCode

Can you solve this real interview question? User Activity for the Past 30 Days I - Table: Activity +---------------+---------+ | Column Name | Type | +---------------+---------+ | user_id | int | | session_id | int | | activity_date | date | | activity_typ

leetcode.com

 

๐Ÿ’ป ๋ฌธ์ œ

Write a solution to find the daily active user count for a period of 30 days ending 2019-07-27 inclusively. A user was active on someday if they made at least one activity on that day. And please note that we do not care about days with zero active users.

Input๊ณผ Output ์˜ˆ์‹œ

 

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

๋”๋ณด๊ธฐ
select activity_date as day, count(distinct(user_id)) as active_users
from Activity
where activity_date between date_sub('2019-07-27', interval 29 day) and '2019-07-27'
group by activity_date

 

๐Ÿ’ป ๋ฌธ์ œ ํ’€์ด

์ด๋ฒˆ ๋ฌธ์ œ๋Š” join์ด๋‚˜ ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•  ํ•„์š”๋Š” ์—†์ง€๋งŒ ๋Œ€์‹  '๋‚ ์งœ'๋ฅผ ์กฐ๊ฑด์œผ๋กœ ํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ด ํ•จ์ •์„ ์ž˜ ํ”ผํ•ด์•ผ ํ•œ๋‹ค.

 

๋ฌธ์ œ๋ฅผ ํ’€์ดํ•˜๊ธฐ์— ์•ž์„œ, <1์›” 1์ผ ~ 1์›” 5์ผ>๊นŒ์ง€์˜ ์ผ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•ด๋ณด์ž. 1์ผ, 2์ผ, 3์ผ, 4์ผ, ๊ทธ๋ฆฌ๊ณ  5์ผ. 5-1์€ 4์ž„์—๋„ ๋ถˆ๊ตฌํ•˜๊ณ  1์„ ์‹œ์ž‘์ผ๋กœ ํฌํ•จํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— (ํ˜น์€ 5์ผ์„ ์ข…๋ฃŒ์ผ๋กœ ํฌํ•จํ–ˆ๊ธฐ ๋•Œ๋ฌธ์—) ์ผ์ˆ˜๋Š” ์ด 5๊ฐ€ ๋œ๋‹ค.

 

๊ทธ๋ ‡๋‹ค๋ฉด ์ด์ œ ๋ฌธ์ œ๋ฅผ ๋‹ค์‹œ ํ•œ ๋ฒˆ ์‚ดํŽด๋ณด์ž. ๋ฌธ์ œ๋ฅผ ๋ณด๋ฉด a period of 30 days ending 2019-07-27 ๋ฅผ ์กฐ๊ฑด์œผ๋กœ ํ•˜๊ณ  ์žˆ๋‹ค. ์ฆ‰, ๋‹ค์‹œ ๋งํ•ด

1๏ธโƒฃ 2019-07-27๊นŒ์ง€ 30์ผ ๋™์•ˆ ์ผ์ผ ํ™œ์„ฑ ์‚ฌ์šฉ์ž ์ˆ˜๋ฅผ ์ฐพ๋Š” ์ฟผ๋ฆฌ๋ฅผ ์ž‘์„ฑํ•˜๋ผ

 

๊ฐ€ ์ด๋ฒˆ ๋ฌธ์ œ์˜ ํ•ต์‹ฌ์ด ๋œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์šฐ๋ฆฌ๋Š” ์‹œ์ž‘์ผ์„ ํฌํ•จํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋‹จ์ˆœ ์ˆซ์ž๋กœ๋งŒ ๊ณ„์‚ฐํ•œ๋‹ค๊ณ  ์น˜๋ฉด (07์›” 27์ผ - ??์›” ??์ผ)์€ 30์ด ์•„๋‹Œ 29๊ฐ€ ๋œ๋‹ค.

select 
from Activity
where activity_date between date_sub('2019-07-27', interval 29 day) and '2019-07-27'

 

๋”ฐ๋ผ์„œ ์œ„ ์ฟผ๋ฆฌ์ฒ˜๋Ÿผ ๊ธฐ์ค€์ผ(2019-07-27)๋กœ๋ถ€ํ„ฐ 29์ผ ๋บ€ ์‹œ์ž‘์ผ๋กœ๋ถ€ํ„ฐ ๊ธฐ์ค€์ผ(2019-07-27)๊นŒ์ง€ ํ™œ๋™ ์ผ์ž๊ฐ€ ์žˆ๋Š” ๋ ˆ์ฝ”๋“œ ์ฐพ๋Š” ์ฟผ๋ฆฌ๋ฅผ where์ ˆ๋กœ ํ’€์–ด๋‚ด๋ฉด ๋œ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•