LeetCode刷题-数据库(MySQL)-1082. Sales Analysis I

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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sales-analysis-i
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、思路分析

Write an SQL query that reports the best seller by total sales price, If there is a tie, report them all.
本题要求找出销售冠军(如果有平手,那就把他们都找出来)。需要注意的有以下几点:

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

三、代码实现

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
	);

你可能感兴趣的:(MySQL)