본문 바로가기
Algorithm/프로그래머스

[프로그래머스] SQL 문제풀이 - 상품을 구매한 회원 비율 구하기

by whdgus928 2023. 6. 3.

https://school.programmers.co.kr/learn/courses/30/lessons/131534

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

내 풀이

1. ONLINE_SALE 테이블을 USER_INFO 테이블의 가입년도가 '2021'인 조건으로 조회한다

2. 2021년에 가입한 회원 중 상품을 구매한 회원수 -> count(distinct user_id) ※ 여러번 구매한 사람이 있어서 중복 처리를 해야한다

3. 2021년에 가입한 전체 회원 수 -> (select count(*) from user_info where year(joined)=2021)

4. 반올림 -> round(대상, 표시할 자리수)  ex) round(4.555 , 1)

SELECT year(sales_date) as year,month(sales_date) as month, count(distinct user_id) as puchased_users,
round(count(distinct user_id)/(select count(*) from user_info where year(joined)=2021),1) as puchased_ratio
from online_sale
where user_id in (select user_id from user_info where year(joined) = 2021)
group by year(sales_date),month(sales_date)
order by year,month

 

배운 점

1. 문제가 복잡할수록 테이블을 먼저 파악하고 문제를 하나씩 따라가본다

2. join을 서브쿼리로 해결할 수도 있다

반응형

댓글