天天看點

【每日SQL打卡】​​​​​​​​​​​​​​​DAY 16丨市場分析 II【難度困難】​

難度困難

SQL架構

表: 

Users

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| user_id        | int     |
| join_date      | date    |
| favorite_brand | varchar |
+----------------+---------+
user_id 是該表的主鍵
表中包含一位線上購物網站使用者的個人資訊,使用者可以在該網站出售和購買商品。           

複制

表: 

Orders

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| order_date    | date    |
| item_id       | int     |
| buyer_id      | int     |
| seller_id     | int     |
+---------------+---------+
order_id 是該表的主鍵
item_id 是 Items 表的外鍵
buyer_id 和 seller_id 是 Users 表的外鍵           

複制

表: 

Items

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| item_id       | int     |
| item_brand    | varchar |
+---------------+---------+
item_id 是該表的主鍵           

複制

寫一個 SQL 查詢确定每一個使用者按日期順序賣出的第二件商品的品牌是否是他們最喜愛的品牌。如果一個使用者賣出少于兩件商品,查詢的結果是 

no

 。

題目保證沒有一個使用者在一天中賣出超過一件商品

下面是查詢結果格式的例子:

Users table:
+---------+------------+----------------+
| user_id | join_date  | favorite_brand |
+---------+------------+----------------+
| 1       | 2019-01-01 | Lenovo         |
| 2       | 2019-02-09 | Samsung        |
| 3       | 2019-01-19 | LG             |
| 4       | 2019-05-21 | HP             |
+---------+------------+----------------+

Orders table:
+----------+------------+---------+----------+-----------+
| order_id | order_date | item_id | buyer_id | seller_id |
+----------+------------+---------+----------+-----------+
| 1        | 2019-08-01 | 4       | 1        | 2         |
| 2        | 2019-08-02 | 2       | 1        | 3         |
| 3        | 2019-08-03 | 3       | 2        | 3         |
| 4        | 2019-08-04 | 1       | 4        | 2         |
| 5        | 2019-08-04 | 1       | 3        | 4         |
| 6        | 2019-08-05 | 2       | 2        | 4         |
+----------+------------+---------+----------+-----------+

Items table:
+---------+------------+
| item_id | item_brand |
+---------+------------+
| 1       | Samsung    |
| 2       | Lenovo     |
| 3       | LG         |
| 4       | HP         |
+---------+------------+

Result table:
+-----------+--------------------+
| seller_id | 2nd_item_fav_brand |
+-----------+--------------------+
| 1         | no                 |
| 2         | yes                |
| 3         | yes                |
| 4         | no                 |
+-----------+--------------------+

id 為 1 的使用者的查詢結果是 no,因為他什麼也沒有賣出
id為 2 和 3 的使用者的查詢結果是 yes,因為他們賣出的第二件商品的品牌是他們自己最喜愛的品牌
id為 4 的使用者的查詢結果是 no,因為他賣出的第二件商品的品牌不是他最喜愛的品牌           

複制