๐ป ๋ฌธ์ ์ฃผ์ : Product Sales Analysis III - LeetCode
Product Sales Analysis III - LeetCode
Can you solve this real interview question? Product Sales Analysis III - Table: Sales +-------------+-------+ | Column Name | Type | +-------------+-------+ | sale_id | int | | product_id | int | | year | int | | quantity | int | | price | int | +---------
leetcode.com
๐ป ๋ฌธ์
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.
* ์ฐธ๊ณ ์ฐจ, ์ ํ ์ด๋ธ ์ค Product ํ ์ด๋ธ์ ์ด๋ฒ ๋ฌธ์ ์์ ์ฌ์ฉํ ์ผ์ด ์๋ค.
๐ป ์ฝ๋ ๋ฏธ๋ฆฌ๋ณด๊ธฐ
select product_id, year as first_year, quantity, price
from Sales
where (product_id, year) in (select product_id, min(year) from Sales group by product_id)
๐ป ๋ฌธ์ ํ์ด
์์์๋ ํ ์ฐจ๋ก ์ธ๊ธํ์ง๋ง ์ฌ๋ฏธ์๊ฒ๋ ์ด๋ฒ ๋ฌธ์ ์์ ์ฃผ์ด์ง ํ ์ด๋ธ Sales์ Product ํ ์ด๋ธ ์ค Product ํ ์ด๋ธ์ ์ฌ์ฉํ์ง ์๊ณ ๋ ํ ์ ์๋ค.
๋ฌธ์ ์ ์ ๊ทผ ๋จ๊ณ๋ ์๋์ ๊ฐ๋ค.
1๏ธโฃ ๊ฐ product_id๋ณ ์ฒซ ๋ฒ์งธ ํ๋งค ์ฐ๋
2๏ธโฃ 1๏ธโฃ์์ ๊ตฌํ ํ๋งค์ฐ๋์ ๋ฑ๋ก๋ id ๋ฐ quantity ๋ฑ ์ ๋ณด select
1๏ธโฃ ๊ฐ product_id๋ณ ์ฒซ ๋ฒ์งธ ํ๋งค์ฐ๋
์ฐ์ 1๏ธโฃ์ ์ดํด๋ณด์. ๊ฐ product_id๋ณ ๊ฐ์ ๊ตฌํ๊ธฐ ์ํด ์ฐ์ ์ด ์ปฌ๋ผ์ group by๋ก ๋ฌถ์ด์ผ ํ๋ค. ๊ทธ๋ฆฌ๊ณ '์ฒซ ๋ฒ์งธ' ํ๋งค์ฐ๋๋ผ๋ ๊ฒ์, ํ๋งค์ฐ๋๊ฐ ๊ฐ์ฅ ์ด๋ฅธ ๊ฒ์ ์๋ฏธํ๋ฉฐ ์ซ์๋ก ๋ฐ์ง๋ฉด ๊ฐ์ด ์ ์ผ ์๊ธฐ์ min() ํจ์๋ฅผ ์จ์ผ ํ๋ค.
select product_id, min(year)
from Sales
group by product_id
๋ค๋ง ์ด์ ์ ํ ๋ฒ ์๊ธฐํ๋ฏ, group by๋ก ๋ฐ์ดํฐ๋ฅผ ๋ฌถ์ ๊ฒฝ์ฐ, ์ฒซ ๋ฒ์งธ ๋ ์ฝ๋๋ฅผ ๊ธฐ์ค์ผ๋ก ๊ฐ์ด ๋ฌถ์ด๊ธฐ ๋๋ฌธ์ ์๋ ํ์ ๊ฐ์ ์ํฉ์ด ๋ฐ์ํ ์ ์๋ค.
Product_id | Year | Quantity |
1 | 2020 | 50 |
1 | 2010 | 30 |
↓ ↓ ↓
Product_id | min(Year) | Quantity |
1 | 2010 | 50 |
product_id๊ฐ 1์ธ ์ํ์ ์ ์ฝ๋๋๋ก ์คํํ๋ค๊ณ ๊ฐ์ ํ๋ฉด min(year)์ ์ฐ๋ฆฌ๊ฐ ์ํ ๋๋ก ์ฒซ ํ๋งค์ฐ๋๊ฐ ์ถ๋ ฅ๋๊ฒ ์ง๋ง ๊ทธ ์ธ์๋ ๋ณ๋ ํจ์ ๋ฑ์ ์ฐ์ง ์๋ ํ ์ฒซ ๋ฒ์งธ ๋ ์ฝ๋๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ฌถ์ด๊ธฐ ๋๋ฌธ์ Qty๋ 30์ด ์๋ 50์ด ๋๋ค. ๋ฐ๋ผ์ ์ฐ๋ฆฌ๋ ์ 1๏ธโฃ ์กฐ๊ฑด์ ์๋ธ์ฟผ๋ฆฌ๋ก ๋ฃ์ด์ ์ถ๋ ฅ๊ฒฐ๊ณผ๋ก ๋์ฌ product_id์ year(min)์ ๊ฐ์ง๋ ๋ ์ฝ๋๋ฅผ ๊ธฐ์ค์ผ๋ก ์กฐ๊ฑด์ ๊ฑธ์ด์ผ ํ๋ค.
select
from Sales
where (product_id, year) in (select product_id, min(year) from Sales group by product_id)
2๏ธโฃ 1๏ธโฃ์์ ๊ตฌํ ํ๋งค์ฐ๋์ ๋ฑ๋ก๋ id ๋ฐ quantity ๋ฑ ์ ๋ณด select
์ด์ ์ฌ๊ธฐ์ ๋ฌธ์ ์กฐ๊ฑด์ธ select๋ก ์ถ์ถํ ์ปฌ๋ผ๋ช ๋ง ๋ฃ์ด์ฃผ๋ฉด ๋ณธ ๋ฌธ์ ๋ ํ๋ฆฐ๋ค.
'SQL > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[SQL50] #27. Find Followers Count (2) | 2024.01.06 |
---|---|
[SQL50] #26. Classes More Than 5 Students (1) | 2024.01.05 |
[LeetCode][SQL50] #24. User Activity for the Past 30 Days I (1) | 2024.01.04 |
[LeetCode][SQL50] #23. Number of Unique Subjects Taught by Each Teacher (1) | 2024.01.03 |
[LeetCode][SQL50] #22. Game Play Analysis IV (0) | 2024.01.02 |