SQL/문제풀이

[LeetCode] Product Sales Analysis 3

응엉잉 2024. 3. 4. 13:39

https://leetcode.com/problems/product-sales-analysis-iii/description/?envType=study-plan-v2&envId=top-sql-50

 

Product Sales Analysis III - LeetCode

Can you solve this real interview question? Product Sales Analysis III - Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

SELECT s.product_id,
    MIN(s.year) AS first_year,
    s.quantity,
    s.price
FROM sales s
    LEFT JOIN product p ON s.product_id = p.product_name
GROUP BY s.product_id

quantity랑 price가 product_id랑 first_year랑 안맞는 문제 발생

product_id에 대해서 첫번쨰 column이 불러와짐!

 

ex) Sales 테이블이 이렇게 생긴 경우

product_id = 69 이면서 MIN(year) 조건을 걸었을 때를 확인해보면 1801년이 first_year 이고 quantity = 2, price = 9908 임을 알 수 있다.

그런데 위의 코드를 실행시켜보면

sales_id 1번의 quantity와 price를 그냥 가져오고 있음을 알 수 있다.

 

따라서

1. product_id별 first_year를 구한 후

SELECT product_id,
	MIN(year) AS first_year
FROM sales
GROUP BY product_id

 

2. 해당 조건을 만족하는 product_id, first_year를 WHERE절 서브쿼리로 가져온 후 필요한 row를 뽑는다.

SELECT product_id,
    year AS first_year,
    quantity,
    price
FROM sales
WHERE (product_id, year) IN
    (SELECT product_id,
        MIN(year) AS first_year
    FROM sales
    GROUP BY product_id)