如何获得特定产品在哪个商店获得最大利益?

How to get in which store did the specific product get the most benefit?

所以,这是我的 tables:

销售额

id product_code store_id
1 4536 1
2 4674 2

产品

product_code product_name price real_price
4536 Red bull energy drink 300 ml 3,68 2,88
4674 Mac coffee 25 gr 2,59 2,10

商店

store_id store_name
1 first
2 second

我需要找到产品 'red bull' 在哪家商店获得的收益最大。效益被认为是price-real_price。数量被认为是 product_code 在销售额 table.

中的重复

预期输出:

product_name benefit store_name
Red bull energy drink 300 ml 4536,4 second

这是我尝试过的:

select 
   products.product_name, (sum( price-real_price)*count(sales.product_code)) as benefit from products
join sales on sales.store_id = stores.store_id
where products.product_name like '%red bull%'
group by products.product_name

但它没有给我想要的输出。

也许像下面这样的查询会有所帮助。 请注意,我使用了 dense rank 函数来获取所有在出现平局时具有相同优势的商店。它还巧妙地允许以后更改逻辑。

demo link

; with benefitperstore as 
(
select 
s.store_name,
P.product_name, 
count(1) * (P.price - P.real_price) as benefit
from Sales X join Stores s 
   on X.Store_id=s.Store_id
join Products P 
   on P.product_code=X.product_code
where product_name like '%red bull%'
group by s.store_name,P.price- P.real_price,P.product_name
)
, mostBenefit as
(
select *, 
dense_rank() over (order by benefit desc) as rn 
from benefitperstore 
)

select 
product_name,
benefit,
store_name
from mostBenefit 
where rn=1

您可以通过按 store_id 分组并按优惠排序来找到相关商店。

select top(1)
   sales.store_id, sum(price-real_price)*count(sales.product_code) as benefit 
from products
join sales on sales.product_code = products.product_code
where products.product_name like '%red bull%'
group by sales.store_id
order by sum(price-real_price)*count(sales.product_code) desc