1、題目描述
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)
2、解題思路
其實和上一題都是差不多的,這次換一種解法
1# 首先,對每個銷售員進行出售價格求和,然後倒序
select seller_id ,sum(price) as p
from Sales
group by seller_id
order by price desc
2# 然後,增加一列排名列 參考 分數排名
select seller_id ,p,@j:=@j+(@i<>(@i:=p)) as rank
3# 最後,就是找出rank=1
的記錄
3、提交記錄
select seller_id
from(
select seller_id ,p,@j:=@j+(@i<>(@i:=p)) as rank
from(
select seller_id ,sum(price) as p
from Sales
group by seller_id
order by price desc)b,(select @i:=0,@j:=0)a)c
where rank=1
order by seller_id