[Leetcode 1082] Sales Analysis I

原题说明

Table: Product

+————–+———+
| Column Name | Type |
+————–+———+
| product_id | int |
| product_name | varchar |
| unit_price | int |
+————–+———+
product_id is the primary key of this table.

Table: Sales

+————-+———+
| Column Name | Type |
+————-+———+
| seller_id | int |
| product_id | int |
| buyer_id | int |
| sale_date | date |
| quantity | int |
| price | int |
+—— ——+———+
This table has no primary key, it can have repeated rows.
product_id is a foreign key to Product table.

 

Write an SQL query that reports the best seller by total sales price, If there is a tie, report them all.

The query result format is in the following example:

Product table:
+————+————–+————+
| product_id | product_name | unit_price |
+————+————–+————+
| 1 | S8 | 1000 |
| 2 | G4 | 800 |
| 3 | iPhone | 1400 |
+————+————–+————+

Sales table:
+———–+————+———-+————+———-+——-+
| seller_id | product_id | buyer_id | sale_date | quantity | price |
+———–+————+———-+————+———-+——-+
| 1 | 1 | 1 | 2019-01-21 | 2 | 2000 |
| 1 | 2 | 2 | 2019-02-17 | 1 | 800 |
| 2 | 2 | 3 | 2019-06-02 | 1 | 800 |
| 3 | 3 | 4 | 2019-05-13 | 2 | 2800 |
+———–+————+———-+————+———-+——-+

Result table:
+————-+
| seller_id |
+————-+
| 1 |
| 3 |
+————-+
Both sellers with id 1 and 3 sold products with the most total price of 2800.


解题思路

题目要求找出最好的seller,如果有一样,那就把他们都找出来。我们需要注意两点:

  1. Sales表中的priceunit_pricequantity的乘积,所以直接将表中对应seller每行的price加和即为销售额。所以,这就需要对seller_id使用GROUP BY后再SUM(price)
  2. 得到每个seller的总销售额以后,按总销售额降序排列,用LIMIT 1取第一个。但这带来的问题是,如果有平手,则无法全部取出。解决方法是,先使用一个子查询得到最好的seller的销售额,然后再查询销售额等于这个的seller即可。

示例代码 (mysql)

1
2
3
4
5
6
7
8
SELECT seller_id
FROM Sales
GROUP BY seller_id
HAVING SUM(price) = (SELECT SUM(price) as pr
FROM Sales
GROUP BY seller_id
ORDER BY pr DESC
LIMIT 1 )

视频讲解

我们在Youtube上更新了视频讲解,欢迎关注!

------ 关注公众号:猩猩的乐园 ------