我需要有关SQL查询的帮助。
我有一张这样的桌子。
我有一个销售表。从销售表中,我需要获取一个类别中一个类别的交易总和。例如,对于类别2中的每个类别,我都希望获得类别1的顶部和销售额的总和。
我可以针对每个类别分别进行设置,但无法获得包含所有类别的表格。
谢谢!
SELECT
[Category 2],
[Category 1] AS [Top Category 1],
[Sum Of Sales]
FROM
(
SELECT [Category 2], [Category 1]
, SUM(t.Sales) AS [Sum Of Sales]
, DENSE_RANK() OVER (PARTITION BY [Category 2] ORDER BY SUM(t.Sales) DESC) AS Rnk
FROM YourSalesTable t
GROUP BY [Category 2], [Category 1]
) q
WHERE Rnk = 1
RANK OVER
对行进行排名,从而使最上面的行排名1。为了仅获取最上面的行,可以使用TOP
。这里需要WITH TIES
子句,因为有几行具有相同的等级1。select top(1) with ties category2, category1, sum(sales) as total
from mytable
group by category2, category1
order by rank() over (partition by category2 order by total desc);