Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 프로젝트
- 회귀분석
- 어쩌다 마케팅
- TiL
- 파이썬 철저 입문
- MySQL
- Cluster
- wil
- SQL
- 프로그래머스
- 텍스트 분석
- R
- 내일배움
- 내일배움카드
- harkerrank
- 스파르타
- 웹 스크랩핑
- 파이썬
- 내일배움캠프
- 실전 데이터 분석 프로젝트
- 스파르타 코딩
- 중회귀모형
- 티스토리챌린지
- 오블완
- 스파르타코딩
- 파이썬 머신러닝 완벽가이드
- 파이썬 머신러닝 완벽 가이드
- hackerrank
- 파이썬 철저입문
- 미세먼지
Archives
- Today
- Total
OkBublewrap
1164. Product Price at a Given Date 본문
Product Price at a Given Date
문제
product_id
와change_date
는 기본키(고유 값을 가지는 컬럼들의 조합)- 2019-08-16에 모든 상품의 가격을 찾는 솔루션 작성
- 모든 상품의 초기 가격(변경 전)은 10 이라고 가정
- 2019-08-16 이전에 바뀐 이력이 있으면 그대로 출력, 없으면 10을 출력
입력 테이블
Products
product_id
new_price
change_date
풀이
1. CTE
고유한 product_id
한 테이블 생성
select distinct product_id
from Products
2. '2019-08-16' 이하인 데이터에서 해당 날짜에 가까운 값 생성 row_number()
row_number()
을 사용하여 가까운 값 가져오기
select product_id, new_price, change_date,
row_number() over (partition by product_id order by change_date desc) as rn
from Products
where change_date <= '2019-08-16'
3. CTE 기준으로 LEFT JOIN 사용
'2019-08-16'에 가장 가까운 값 = 1으로 JOIN
select t1.product_id, coalesce(t2.new_price, 10) as price
from temp_01 t1
left join temp_02 t2 on t1.product_id = t2.product_id
and t2.rn = 1
4. 전체 코드
with temp_01 as
(
select distinct product_id
from Products
), temp_02 as (
select product_id, new_price, change_date,
row_number() over (partition by product_id order by change_date desc) as rn
from Products
where change_date <= '2019-08-16'
)
select t1.product_id, coalesce(t2.new_price, 10) as price
from temp_01 t1
left join temp_02 t2 on t1.product_id = t2.product_id
and t2.rn = 1
'개발 > SQL' 카테고리의 다른 글
1484. Group Sold Products By The Date (0) | 2025.02.01 |
---|---|
Google Big Query(with 리눅스) (0) | 2025.01.25 |
180. Consecutive Numbers (0) | 2025.01.22 |
1070. Product Sales Analysis III (0) | 2025.01.22 |
1934. Confirmation Rate (0) | 2025.01.21 |