문제
Write a solution to select the product id, year, quantity, and price for the first year of every product sold.
Return the resulting table in any order. The result format is in the following example.
판매된 모든 제품에 대해서, 첫해의 가격, 연도, 제품ID, 수량을 선택하시오.
정렬 순서는 상관없다.
테이블 및 예제
[Sales]
+-------------+-------+
| Column Name | Type |
+-------------+-------+
| sale_id | int |
| product_id | int |
| year | int |
| quantity | int |
| price | int |
+-------------+-------+
[Product]
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| product_id | int |
| product_name | varchar |
+--------------+---------+
[Example]
Input:
Sales table:
+---------+------------+------+----------+-------+
| sale_id | product_id | year | quantity | price |
+---------+------------+------+----------+-------+
| 1 | 100 | 2008 | 10 | 5000 |
| 2 | 100 | 2009 | 12 | 5000 |
| 7 | 200 | 2011 | 15 | 9000 |
+---------+------------+------+----------+-------+
Product table:
+------------+--------------+
| product_id | product_name |
+------------+--------------+
| 100 | Nokia |
| 200 | Apple |
| 300 | Samsung |
+------------+--------------+
Output:
+------------+------------+----------+-------+
| product_id | first_year | quantity | price |
+------------+------------+----------+-------+
| 100 | 2008 | 10 | 5000 |
| 200 | 2011 | 15 | 9000 |
+------------+------------+----------+-------+
풀이
RANK() 사용하기
제품 별로 첫해를 뽑아내기 위해서 제품의 판매 년도 순으로 rank를 생성한다.
SELECT product_id, year, quantity, price,
RANK() OVER (PARTITION BY product_id ORDER BY year) AS row_num
FROM sales;
product_id 별로 그룹화를 하고, year 순으로 정렬을 해준 후에 rank를 생성한다.
| product_id | year | quantity | price | row_num |
| ---------- | ---- | -------- | ----- | ------- |
| 100 | 2008 | 10 | 5000 | 1 |
| 100 | 2009 | 12 | 5000 | 2 |
| 200 | 2011 | 15 | 9000 | 1 |
이 쿼리를 서브쿼리로 이용해서 rank(row_num)이 1인 경우를 선택하면 된다.
WITH mins AS (
SELECT product_id, year, quantity, price,
RANK() OVER (PARTITION BY product_id ORDER BY year) AS row_num
FROM sales
)
SELECT m.product_id, m.year AS first_year, m.quantity, m.price
FROM mins AS m
WHERE m.row_num = 1;
'코딩테스트 > SQL' 카테고리의 다른 글
SQL > LeetCode 180. Consecutive Numbers (MySQL) (0) | 2024.06.10 |
---|---|
SQL > LeetCode 619. Biggest Single Number (MySQL) (0) | 2024.06.07 |
SQL > LeetCode 550. Game Play Analysis IV (MySQL) (0) | 2024.06.04 |
SQL > LeetCode 1193. Monthly Transactions I (MySQL) (2) | 2024.06.02 |
SQL > LeetCode 1633. Percentage of Users Attended a Contest(MySQL) (1) | 2024.05.29 |