我正在尝试从3个表构建查询。销售,商店和物品。 目标是获得销量最高的10种产品,并让每种产品展示销售额最低的商店。 我有以下查询,但由于它也指向store_desc,因此无法获得最独特的产品。目标是在没有商店描述的情况下获得销量最高的前10种产品,然后获得数量最少的“ a”
select distinct top 10 sum(net_sale) as sales, sum(quantity)
as a, sales.item_code,stores.store_desc from sales join
stores on stores.store_code=sales.store_code group by
sales.net_sale, sales.item_code,stores.store_desc order by
sales desc
答案 0 :(得分:0)
您可以使用以下方法获得每个商店的每种产品的销售额:
select s.store_code, s.item_code, sum(i.quantity) as qty
from sales s
group by s.store_code, s.item_code;
添加一个,我们就可以得出每个商店的总数量:
select s.store_code, s.item_code, sum(i.quantity) as qty,
sum(sum(i.quantity)) over (partition by s.item_code) as item_qty
from sales s
group by s.store_code, s.item_code;
然后,以此为子查询,我们可以枚举它们:
select s.*,
dense_rank() over (order by item_qty desc) as item_rank,
row_number() over (partition by item_code order by qty asc) as item_store_rank
from (select s.store_code, s.item_code, sum(i.quantity) as qty,
sum(sum(i.quantity)) over (partition by s.item_code) as item_qty
from sales s
group by s.store_code, s.item_code
) s
然后将其设为子查询。您想要:
where item_rank <= 10 and item_store_rank <= 3
注意:这不考虑不出售某些商品的商店。如果这是一个问题,我建议您提出一个 new 问题,并明确说明如何处理此类情况。