데이터 분석

1084. Sales Analysis III | Easy 본문

SQL/leetcode

1084. Sales Analysis III | Easy

딱한아이 2025. 1. 21. 17:11
문제

 

Write a solution to report the products that were only sold in the first quarter of 2019. That is, between 2019-01-01 and 2019-03-31 inclusive.

테이블 정보

 

2019년 1분기에만 팔린 상품을 조회하는 문제이다.

 

Solution

✔️ 쿼리 1

SELECT product_id
     , product_name
FROM Product
WHERE product_id IN (
    SELECT product_id
    FROM Sales
    GROUP BY product_id
    HAVING MIN(sale_date) >= '2019-01-01' AND MAX(sale_date) <= '2019-03-31'
)

 

✅ WHERE절에 서브쿼리를 사용한 방법 

 

✔️ 쿼리 2

SELECT s.product_id
     , p.product_name
FROM Sales s
JOIN Product p ON s.product_id = p.product_id
GROUP BY s.product_id
HAVING MIN(s.sale_date) >= '2019-01-01' 
   AND MAX(s.sale_date) <= '2019-03-31'

 

✅ Product 테이블과 Sales 테이블을 조인한 방법

 

피드백

나는 처음에 아래와 같이 접근했다. 하지만 이 쿼리에는 HAVING 절 조건 부분에 문제가 있다. 이렇게 작성할 경우, 여러 번 판매된 상품 중 최소 판매 날짜가 1분기에 해당되는지만 판단하게 되어, 1분기 외에 판매된 경우도 포함될 수 있다. 따라서 이 쿼리는 문제를 해결하기에 적절하지 않다.

SELECT product_id
     , product_name
FROM Product
WHERE product_id IN (
    SELECT product_id
    FROM Sales
    GROUP BY product_id
    HAVING MIN(sale_date) BETWEEN '2019-01-01' AND '2019-03-31'
 )