1+ 1070 . Product Sales Analysis III
2+ Medium
3+ Topics
4+ Companies
5+ SQL Schema
6+ Pandas Schema
7+ Table: Sales
8+
9+ + -- -----------+-------+
10+ | Column Name | Type |
11+ + -- -----------+-------+
12+ | sale_id | int |
13+ | product_id | int |
14+ | year | int |
15+ | quantity | int |
16+ | price | int |
17+ + -- -----------+-------+
18+ (sale_id, year) is the primary key (combination of columns with unique values ) of this table.
19+ product_id is a foreign key (reference column) to Product table.
20+ Each row of this table shows a sale on the product product_id in a certain year.
21+ Note that the price is per unit.
22+
23+
24+ Table: Product
25+
26+ + -- ------------+---------+
27+ | Column Name | Type |
28+ + -- ------------+---------+
29+ | product_id | int |
30+ | product_name | varchar |
31+ + -- ------------+---------+
32+ product_id is the primary key (column with unique values ) of this table.
33+ Each row of this table indicates the product name of each product.
34+
35+
36+ Write a solution to select the product id, year, quantity, and price for the first year of every product sold.
37+
38+ Return the resulting table in any order.
39+
40+ The result format is in the following example.
41+
42+
43+
44+ Example 1 :
45+
46+ Input:
47+ Sales table:
48+ + -- -------+------------+------+----------+-------+
49+ | sale_id | product_id | year | quantity | price |
50+ + -- -------+------------+------+----------+-------+
51+ | 1 | 100 | 2008 | 10 | 5000 |
52+ | 2 | 100 | 2009 | 12 | 5000 |
53+ | 7 | 200 | 2011 | 15 | 9000 |
54+ + -- -------+------------+------+----------+-------+
55+ Product table:
56+ + -- ----------+--------------+
57+ | product_id | product_name |
58+ + -- ----------+--------------+
59+ | 100 | Nokia |
60+ | 200 | Apple |
61+ | 300 | Samsung |
62+ + -- ----------+--------------+
63+ Output:
64+ + -- ----------+------------+----------+-------+
65+ | product_id | first_year | quantity | price |
66+ + -- ----------+------------+----------+-------+
67+ | 100 | 2008 | 10 | 5000 |
68+ | 200 | 2011 | 15 | 9000 |
69+ + -- ----------+------------+----------+-------+
70+
71+
72+
73+ # Write your MySQL query statement below
74+ SELECT
75+ product_id,
76+ year AS first_year,
77+ quantity,
78+ price
79+ FROM
80+ Sales
81+ WHERE
82+ (product_id, year) IN (
83+ SELECT
84+ product_id,
85+ MIN (year) AS year
86+ FROM
87+ Sales
88+ GROUP BY
89+ product_id
90+ );
0 commit comments