카테고리 없음
[SQL 코드카타] 100 ~ 104번 (LeetCode)
doo_
2024. 1. 14. 16:21
100번. user-activity-for-the-past-30-days-i
select
activity_date as day,
count(distinct user_id) as active_users -- 3) 그 기간마다 한 번이라도 접속한 유저의 수 조회
from
activity
where -- 1) 기간 조건을 걸고
activity_date between '2019-06-28' and '2019-07-27'
group by
activity_date -- 2)기간을 그룹화해줘서
101번 product-sales-analysis-iii
select -- 2) 조회하기
product_id, year as first_year, quantity, price
from
sales
where -- 1) 해당 제품id를 기준으로 가장 빠른 연도에 해당하는 조건
(product_id, year) in (select product_id, min(year)
from sales
group by product_id)
> 이것과의 차이는?
select -- 2) 첫 판매년도
product_id, min(year) as first_year, quantity, price
from
sales
group by -- 1) 제품id를 기준으로
product_id
102번 classes-more-than-5-students
select
class
from
courses
group by
class
having
count(student) >= 5
103번 find-followers-count
select
user_id,
count(user_id) as followers_count
from
followers
group by
user_id
order by
1 asc
Q. 서로 맞팔한 id끼리 조회하기
select
*
from
followers f1
left join followers f2
on f1.user_id = f2.follower_id -- 1) f1 user_id와 f2 follower_id가 같게 조인
where
f1.follower_id = f2.user_id -- 2) 그 후 f1.follower_id와 f2.user_id 같은 조건
select
case when max(num) is null then null -- 3) 만약 개수가 1개인 num이 없을 때 null 조회
else max(num) end as num -- 2) 그 num들 중에서 가장 큰 수 조회
from
mynumbers
where
num in (select num
from mynumbers
group by num
having count(num) = 1 -- 1) 개수가 1개인 num들을 조회