題目會給我們兩張資料表,第一張是Sales,第二張是Product。
第一張是Sales表格,裡面分別有sale_id、 product_id、year、quantity、price等欄位。其中(sale_id、 product_id)做為複合主鍵Primary key
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 of this table shows a sale on the product product_id in a certain year.
Note that the price is per unit.
第二張是Product表格,裡面分別有product_id 、 product_name 等欄位。其中 product_id做為主鍵Primary key
Table: Product
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| product_id | int |
| product_name | varchar |
+--------------+---------+
product_id is the primary key (column with unique values) of this table.
Each row of this table indicates the product name of each product.
要求我們,以第一次銷售出去的年份為基準,
列出銷售出去的 product_id, year, quantity, 和 price。
輸出的順序不拘。
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 |
+---------+------------+------+----------+-------+
Product table:
+------------+--------------+
| product_id | product_name |
+------------+--------------+
| 100 | Nokia |
| 200 | Apple |
| 300 | Samsung |
+------------+--------------+
Output:
+------------+------------+----------+-------+
| product_id | first_year | quantity | price |
+------------+------------+----------+-------+
| 100 | 2008 | 10 | 5000 |
| 200 | 2011 | 15 | 9000 |
+------------+------------+----------+-------+
考點主要落在抓取"第一次銷售出去的年份",這邊可以使用subquery,SQL查詢裡面再包著另一個(SQL)子查詢的技巧,找出來。
一般常見的通則樣貌:
SELECT ...欄位 FROM ...表格
WHERE ...欄位 ... 做條件判斷(
包著另一個SQL 查詢語法
)
每個產品的第一次銷售出去的年分,用SQL語法來寫,其實就是
SELECT product_id, MIN(year) as year
FROM Sales
GROUP BY product_id
其中 MIN(year)就對應到題目所要求的"第一次銷售出去的年分"。
GROUP BY product_id 則是由商品編號product_id去做分群。
# Write your MySQL query statement below
SELECT product_id, year AS first_year, quantity, price
FROM Sales
# Select the product id, year, quantity, and price for the first year of every product sold.
WHERE (product_id, year) IN (
SELECT product_id, MIN(year) as year
FROM Sales
GROUP BY product_id
);
掌握子查詢的語法與架構
SELECT ...欄位 FROM ...表格
WHERE ...欄位 ... 做條件判斷(
包著另一個SQL 查詢語法
)
Reference:
[1] MySQL by subquery on composite fields - Product Sales Analysis III - LeetCode