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
- HackerRank
- Inventory Optimization
- MySQL
- ABC Analysis
- Gaimification
- 프로그래머스
- kaggle
- 코딩테스트
- 데이터분석
- forecast
- SKU Consolidation
- 신경쓰기의 기술
- Product Demand
- MS SQL Server
- eda
- tensorflow
- 파이썬
- SQL
- 당신의 인생이 왜 힘들지 않아야 한다고 생각하십니까
- TensorFlowGPU
- 피그마인디언
- 코딩테스트연습
- pandas profiling
- leetcode
- oracle
- 딥러닝
- ModelCheckPoint
- Labor Management System
- ProfileReport
- 웨어하우스 보관 최적화
Archives
- Today
- Total
오늘도 배운다
1158. Market Analysis I / LeetCode, SQL, MySQL 본문
문제
source: LeetCode
Write an SQL query to find for each user, the join date and the number of orders they made as a buyer in 2019.
Return the result table in any order.
제출답안(MySQL)
WITH buyer_2019
AS(
SELECT buyer_id, COUNT(order_id) AS orders_in_2019
FROM orders
WHERE YEAR(order_date) = 2019
GROUP BY buyer_id
)
SELECT
user_id AS buyer_id,
join_date,
CASE WHEN user_id IN (SELECT buyer_id FROM buyer_2019)
THEN orders_in_2019
ELSE 0
END AS orders_in_2019
FROM users AS u
LEFT JOIN buyer_2019 AS b
ON b.buyer_id = u.user_id
풀이(MySQL)
더보기
목표: 2019년 주문하지 않은 사람의 수를 0으로 표기해야함
2019년 오더한 사람들과 오더 수를 담은 CTE 생
WITH buyer_2019
AS(
SELECT buyer_id, COUNT(order_id) AS orders_in_2019
FROM orders
WHERE YEAR(order_date) = 2019
GROUP BY buyer_id
)
>> buyer_2019 는 2019년 오더한 사람의 id와 주문 횟수를 보여줌
users와 buyer_2019를 조인
SELECT
user_id AS buyer_id,
join_date,
CASE WHEN user_id IN (SELECT buyer_id FROM buyer_2019)
THEN orders_in_2019
ELSE 0
END AS orders_in_2019
FROM users AS u
LEFT JOIN buyer_2019 AS b
ON b.buyer_id = u.user_id
>> 주문한 사람을 보여주기 위해서는 buyer_2019의 buyer_id가 아니라 전체 유저의 id를 보여줘야함. 따라서 user_id를 SELECT하고 이름만 바꾸어 주었음
>> 주문횟수의 경우, 2019년에 있으면 buyer_2019의 오더주문을 쓰고 없을경우 0을 반환하게 CASE WHEN 사용
(user_id가 buyer_2019의 buyer_id에 속한다면 orders_in_2019값 활용, 없을 경우 0 반)
문제 바로가기(MySQL)
728x90
'코딩테스트연습(SQL)' 카테고리의 다른 글
1393. Capital Gain/Loss / Leet Code, SQL, MySQL (0) | 2023.03.10 |
---|---|
626. Exchange Seats / LeetCode, SQL, MySQL (0) | 2023.03.10 |
184. Department Highest Salary / LeetCode, SQL, MySQL (0) | 2023.03.05 |
177. Nth Highest Salary / LeetCode, SQL, MySQL (0) | 2023.03.05 |
180. Consecutive Numbers / LeetCode, SQL, MySQL (0) | 2023.03.04 |
Comments