Easy and Simple Solution | Beginner-friendly🚀
CodeIf you found this solution helpful, please give it an upvote! 🌟✨ It really motivates me to share more solutions like this. 😊👍
Happy coding! 💻🐱‍🏍
IntuitionWe
# Code
```mysql []
# Write your MySQL query statement below
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)
```
**If you found this solution helpful, please give it an upvote! 🌟✨ It really motivates me to share more solutions like this. 😊👍
Happy coding! 💻🐱‍🏍**
<img src="https://assets.leetcode.com/users/images/6e8c623a-1111-4d21-9a5b-54e00e7feabb_1738093236.165277.jpeg" width=250px>
# Intuition
We need to find the **first year** each product appeared in the `Sales` table along with its `quantity` and `price` for that year. The `Sales` table contains multiple records for different `product_id`s over different `year`s, so we must identify the earliest year for each product.

# Approach
1. **Find the earliest year each product was sold**  
   - Use `MIN(year)` to get the first occurrence of each `product_id`.  
   - Group by `product_id` to ensure we retrieve only the first year.

2. **Filter only records corresponding to the first year**  
   - Use a `WHERE (product_id, year) IN (...)` condition to match rows where `year` is the **earliest year** for that `product_id`.

3. **Select the required columns**  
   - Return `product_id`, rename `year` as `first_year`, and include `quantity` and `price`.

# Complexity Analysis
- **Finding the first year (`MIN(year) GROUP BY product_id`)**  
  - This requires scanning and grouping by `product_id`, leading to **O(N log P)** complexity, where `P` is the number of unique products.

- **Filtering with `IN` clause**  
  - The `(product_id, year) IN (...)` condition involves checking each record against the first-year subquery, leading to approximately **O(N log P)** complexity.

- **Final selection of columns (`SELECT product_id, year, quantity, price`)**  
  - Runs in **O(N)**.

### **Overall Complexity:**
- The dominant steps are **grouping and filtering**, leading to an approximate **O(N log P) ≈ O(N log N)** complexity in the worst case.
['MySQL']