力扣1082(MySQL)-销售分析Ⅰ(简单)
题目:
产品表:Product
销售表:Sales
编写一个 SQL 查询,查询总销售额最高的销售者,如果有并列的,就都展示出来。
以 任意顺序 返回结果表。
查询结果格式如下所示。
Product 表:
Sales 表:
Result 表:
建表语句:
1 DROP table if exists Product_1082, Sales_1082; 2 Create table If Not Exists Product_1082 (product_id int, product_name varchar(10), unit_price int); 3 Create table If Not Exists Sales_1082 (seller_id int, product_id int, buyer_id int, sale_date date, quantity int, price int); 4 Truncate table Product_1082; 5 insert into Product_1082 (product_id, product_name, unit_price) values ('1', 'S8', '1000'),('2', 'G4', '800'),('3', 'iPhone', '1400'); 6 Truncate table Sales_1082; 7 insert into Sales_1082 (seller_id, product_id, buyer_id, sale_date, quantity, price) values ('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');
解题思路:
本题只涉及 Sales 表:
- 先将 Sales 表中按seller_id,统计出他们的销售总额以及按照总额进行降序排序,相同的排序数一致
- 最后筛选出排序数为1的数据行即可。
1 select seller_id 2 from ( 3 -- 可以直接一步到位:select seller_id,dense_rank() over(order by sum(price) desc) as rnk 4 select seller_id,sum(price) as cout,dense_rank() over(order by cout desc) as rnk 5 from sales_1082 6 group by seller_id 7 )as temp 8 where rnk = 1;