|
| 1 | +/* |
| 2 | +Product Sales Analysis III |
| 3 | +
|
| 4 | +Table: Sales |
| 5 | +
|
| 6 | ++-------------+-------+ |
| 7 | +| Column Name | Type | |
| 8 | ++-------------+-------+ |
| 9 | +| sale_id | int | |
| 10 | +| product_id | int | |
| 11 | +| year | int | |
| 12 | +| quantity | int | |
| 13 | +| price | int | |
| 14 | ++-------------+-------+ |
| 15 | +sale_id is the primary key of this table. |
| 16 | +product_id is a foreign key to Product table. |
| 17 | +Note that the price is per unit. |
| 18 | +Table: Product |
| 19 | +
|
| 20 | ++--------------+---------+ |
| 21 | +| Column Name | Type | |
| 22 | ++--------------+---------+ |
| 23 | +| product_id | int | |
| 24 | +| product_name | varchar | |
| 25 | ++--------------+---------+ |
| 26 | +product_id is the primary key of this table. |
| 27 | + |
| 28 | +
|
| 29 | +Write an SQL query that selects the product id, year, quantity, and price for the first year of every product sold. |
| 30 | +
|
| 31 | +The query result format is in the following example: |
| 32 | +
|
| 33 | +Sales table: |
| 34 | ++---------+------------+------+----------+-------+ |
| 35 | +| sale_id | product_id | year | quantity | price | |
| 36 | ++---------+------------+------+----------+-------+ |
| 37 | +| 1 | 100 | 2008 | 10 | 5000 | |
| 38 | +| 2 | 100 | 2009 | 12 | 5000 | |
| 39 | +| 7 | 200 | 2011 | 15 | 9000 | |
| 40 | ++---------+------------+------+----------+-------+ |
| 41 | +
|
| 42 | +Product table: |
| 43 | ++------------+--------------+ |
| 44 | +| product_id | product_name | |
| 45 | ++------------+--------------+ |
| 46 | +| 100 | Nokia | |
| 47 | +| 200 | Apple | |
| 48 | +| 300 | Samsung | |
| 49 | ++------------+--------------+ |
| 50 | +
|
| 51 | +Result table: |
| 52 | ++------------+------------+----------+-------+ |
| 53 | +| product_id | first_year | quantity | price | |
| 54 | ++------------+------------+----------+-------+ |
| 55 | +| 100 | 2008 | 10 | 5000 | |
| 56 | +| 200 | 2011 | 15 | 9000 | |
| 57 | ++------------+------------+----------+-------+ |
| 58 | +*/ |
| 59 | + |
| 60 | +# SOLUTION by yizi_winnie |
| 61 | +SELECT product_id, year AS first_year, quantity, price |
| 62 | +FROM Sales |
| 63 | +WHERE (product_id, year) IN (SELECT product_id, MIN(year) AS year |
| 64 | + FROM Sales s |
| 65 | + GROUP BY product_id) |
0 commit comments