| comments | true | |
|---|---|---|
| difficulty | Medium | |
| edit_url | https://github.com/doocs/leetcode/edit/main/solution/1000-1099/1070.Product%20Sales%20Analysis%20III/README_EN.md | |
| tags |
|
Table: Sales
+-------------+-------+
| Column Name | Type |
+-------------+-------+
| sale_id | int |
| product_id | int |
| year | int |
| quantity | int |
| price | int |
+-------------+-------+
(sale_id, year) is the primary key (combination of columns with unique values) of this table.
product_id is a foreign key (reference column) to Product table.
Each row records a sale of a product in a given year.
A product may have multiple sales entries in the same year.
Note that the per-unit price.
Write a solution to find all sales that occurred in the first year each product was sold.
-
For each
product_id, identify the earliestyearit appears in theSalestable. -
Return all sales entries for that product in that year.
Return a table with the following columns: product_id, first_year, quantity, and price.
Return the result in any order.
Example 1:
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 | +---------+------------+------+----------+-------+ Output: +------------+------------+----------+-------+ | product_id | first_year | quantity | price | +------------+------------+----------+-------+ | 100 | 2008 | 10 | 5000 | | 200 | 2011 | 15 | 9000 | +------------+------------+----------+-------+
# 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) AS year
FROM Sales
GROUP BY product_id
);# Write your MySQL query statement below
WITH
T AS (
SELECT
*,
RANK() OVER (
PARTITION BY product_id
ORDER BY year
) AS rk
FROM Sales
)
SELECT product_id, year AS first_year, quantity, price
FROM T
WHERE rk = 1;