leetcode1070. 产品销售分析 III(SQL)
銷售表?Sales:
+-------------+-------+
| Column Name | Type ?|
+-------------+-------+
| sale_id ? ? | int ? |
| product_id ?| int ? |
| year ? ? ? ?| int ? |
| quantity ? ?| int ? |
| price ? ? ? | int ? |
+-------------+-------+
sale_id 是此表的主鍵。
產品 ID 是產品表的外鍵。
請注意,價格是按每單位計的。
產品表?Product:
+--------------+---------+
| Column Name ?| Type ? ?|
+--------------+---------+
| product_id ? | int ? ? |
| product_name | varchar |
+--------------+---------+
產品 ID 是此表的主鍵。
?
編寫一個 SQL 查詢,選出每個銷售產品的 第一年 的 產品 id、年份、數量?和 價格。
查詢結果格式如下:
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 ? ? ?|
+------------+--------------+
Result table:
+------------+------------+----------+-------+
| product_id | first_year | quantity | price |
+------------+------------+----------+-------+?
| 100 ? ? ? ?| 2008 ? ? ? | 10 ? ? ? | 5000 ?|
| 200 ? ? ? ?| 2011 ? ? ? | 15 ? ? ? | 9000 ?|
+------------+------------+----------+-------+
思路:先查出每個商品對應的最早時間方便查詢,注意in的應用,可以是多字段對應多字段。
select product_id,year first_year,quantity,price from Sales where (product_id,year) in (select product_id,min(year) from Sales group by product_id);?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的leetcode1070. 产品销售分析 III(SQL)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 郁郁寡欢是什么意思(广袤无垠的是什么意思
- 下一篇: 美国城市大小排名(美国一线城市排名)