[英]Ranking at Multiple Levels on SQL Server
I've read a few ways of doing this, but it does not seem to work for me.我已经阅读了几种执行此操作的方法,但它似乎对我不起作用。 I'm trying to pull data that has a Category, Itemcode, and Sales.
我正在尝试提取具有类别、商品代码和销售额的数据。 I'm summing this up for a period of time so that my basic query looks like this:
我总结了一段时间,所以我的基本查询如下所示:
select
Category
, Itemcode
, sum(Sales)
, rank() over (partition by Category order by sum(Sales) desc) as ItemRank
from
Sales
group by
Category, Itemcode
When I do that, my data looks like this:当我这样做时,我的数据如下所示:
What I would like to do is to add another rank that would show the rank of the Category as a whole.我想做的是添加另一个排名,以显示整个类别的排名。
Something like this:是这样的:
What would the query look like with that added in?添加后的查询会是什么样子? I've tried several things, but I can't seem to get it to work.
我已经尝试了几件事,但我似乎无法让它发挥作用。
Taking a guess here, but I gather you want to rank based on the TotalSales?在这里猜测一下,但我知道你想根据 TotalSales 进行排名? If so, you can join to a subquery to do the aggregation, then use that in another rank column:
如果是这样,您可以加入子查询进行聚合,然后在另一个排名列中使用它:
declare @Sales table (Category varchar(25), ItemCode int, Sales int)
insert into @Sales
values
('Category A', 123, 100),
('Category A', 234, 125),
('Category A', 345, 97),
('Category B', 456, 354),
('Category B', 567, 85),
('Category B', 678, 112)
select
s.Category
, Itemcode
, sum(s.Sales)
, rank() over (partition by s.Category order by sum(Sales) desc) as ItemRank
, dense_rank() over (order by sum(TotalSales) desc) as CategoryRank
from @Sales s
join ( select Category, sum(Sales) as TotalSales
from @Sales
group by Category
) d
on s.Category = d.Category
group by s.Category, Itemcode
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.