본문 바로가기
취준/코팅 테스트

[LeetCode] - 1070.Product Sales Analysis 3

by 소복소복뚜벅뚜벅 2024. 4. 15.

문제 

Write a solution to select the product id, year, quantity, and pricefor the first year of every product sold.
Return the resulting table in any order.
The result format is in the following example.

 

 

"판매되는 모든 제품의 첫 해 제품 id, 연도, 수량, 가격을 선택할 수 있는 솔루션을 작성하시오."

 

풀이 과정 

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

 

주의해야 할 점 

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

 

위의 쿼리의 경우, 역시 첫 해의 제품의 특징을 가져오는 쿼리 같지만, GROUP BY product_id를 이용할 경우, 무조건 첫 해의 년도의 quauntity, price를 가져오지는 않는다. 최소년도의 첫 행을 가져오는 것이므로 주의해야 한다.