07/02 SQL 문제풀이 - (⭐⭐⭐) 1596. The Most Frequently Ordered Products for Each Customer (Leetcode)

Data Architect / Engineer·2024년 7월 2일
1

1일_1SQL

목록 보기
62/63
post-thumbnail

문제

  • LeetCode SQL 문제
  • 1596. The Most Frequently Ordered Products for Each Customer / Medium
  • 문제 내용 : [링크]


내가 작성한 Query

WITH temp_01 AS(
    SELECT customer_id
        , product_id
        , RANK() over(partition by customer_id order by COUNT(*) desc) AS rnum
    FROM orders
    GROUP BY customer_id, product_id
)
SELECT t.customer_id
    , t.product_id
    , p.product_name
FROM temp_01 t
    JOIN products p on t.product_id = p.product_id
WHERE t.rnum = 1
  • customer_id 별, 가장 주문 건수가 많은 product_id 제품을 구하기 위해, 먼저 고객/제품별 주문 건수와 주문 건수에 따른 순위를 포함하는 임시 테이블 temp_01을 구한다.

  • 즉, customer_id, product_id별 집계 데이터를 구해야하므로 이 두 컬럼을 기준으로 GROUP BY 해준다.

  • RANK() Window Function을 통해 customer_id, product_id별 데이터 개수가 많은 순으로(내림차순으로) 순위를 구해준다.

  • temp_01customer_id, product_idProducts 테이블의 제품명(product_name) 데이터를 출력해야 하므로, product_id 기준으로 JOIN 한다.

  • temp_01에서 구한 데이터 중, customer_id 별 구매 건수가 많은 product_id를 구해야 하므로 WHERE 절에 rnum = 1 조건을 준다.


⭐⭐⭐

  • Window Function(rank) 함수를 통해 customer_id별 가장 구매 건수에 따른product_id의 순위를 구하면 해결할 수 있다.

profile
질문은 계속돼 아오에

0개의 댓글