LeetCode_4. Sorting and Grouping
https://leetcode.com/studyplan/top-sql-50/
2356. Number of Unique Subjects Taught by Each Teacher
문제 : 각 교사가 대학에서 가르치는 고유 과목의 수 계산
1. group by로 teacher_id의 데이터 묶기 (1, 2)
2. count(distinct ( ) ) 로 (1, 2)의 subject_id 중복제거 후 개수 세기
select teacher_id, count(distinct(subject_id)) as cnt
from teacher
group by 1
;
1141. User Activity for the Past 30 Days
문제 : 2019년 7월 27일까 30일 동안의 일일 활성 사용자 수 찾기
(적어도 하나의 활동을 했다면 active user 취급)
1. 한 달 간으로 날짜 제한
2. 날짜별 분류 (결과 : 7/21, 7/20)
3. count(distinct(user_id)) : 카운트 ( 고유 사용자 ( 해당 날짜에 활동한 사람 수 ) )
select activity_date as day, count(distinct(user_id)) as active_users
from activity
where activity_date between '2019-06-28' and '2019-07-27'
group by 1
;
1070. Product Sales Analysis III
문제 : 각 제품이 팔리기 시작한 첫번째 년도의 product id, year, quantity, and price 구하기
필요 : 가장 처음 팔린 연도 행
- SubQuery, Self Join : 특정 조건 필터링 후, 그에 대응되는 열 가져오기 위함
- Window Function : ~
- 튜플 묶음 where (product_id, year) in ...
: year도 함께 비교함으로써, 특정 제품의 첫 연도 행 데이터를 필터링 할 수 있게 함
-- SubQuery
select product_id, year as first_year, quantity, price
from sales
where (product_id, year) in (
select product_id, min(year) -- 100, 2008(O), 100, 2009(X)
from sales
group by 1
);
-- Self Join : 특정 조건의 행만 원본 데이터에서 뽑을 때 유용
-- s1 : 제품 판매 정보, s2 : 제품이 처음 팔린 연도 정보
select s1.product_id, s1.year as first_year, s1.quantitiy, s1.price
from sales s1
inner join (
select product_id, min(year) as min_year
from sales
group by product_id
) s2 on s1.product_id = s2.product_id and s1.year = s2.year
;
-- Window Function
select product_id, year as first_year, quantity, price
from (
select *,
row_number() over (partition by product_id order by year) as rn -- 제품별로 나누고, 연도 순 정렬
FROM sales
) as ranked
where rn = 1 -- 제품별 첫 행만 추출
;
2025.04.05 - [SQL/SQL 개념정리] - SubQuery, SelfJoin, WindowFunction 비교
596. Classes More Than 5 Students
문제 : 학생이 5명 이상인 교실 추출
select class
from courses
group by 1 -- 1. class별로 그룹 만들기
having count(student) >= 5 -- 2. 각 그룹 안에서 학생 수 카운트
;
1729. Find Followers Count
문제 : 각 유저의 팔로워 수 구하기
select user_id, count(followers_id) as followers_count
from followers
group by 1
order by 1
;
619. Biggest Single Number
문제 : 혼자 있는 가장 큰 숫자 구하기
SubQuery
1. num 그룹화 후, 값의 개수가 2 미만인 경우 필터링 (혼자 있는 수 구하기)
2. max(num) : 혼자 있는 수 중 가장 큰 수
select max(num) as num
from mynumbers
where num in (
select num
from mynumbers
group by num
having count(num) < 2
);
1045. Customers Who Bought All Products
문제 : Product table 안에 있는 모든 상품을 산 소비자 구하기
단계:
select customer_id
from customer
group by customer_id -- 1. 손님 그룹화 (1, 2, 3)
having count(distinct product_key) = (select count(*) from product) -- 2. 2개 산 사람 = 상품 개수 2개
;