简体   繁体   中英

SQL Double Group by query

I need some help with a SQL Query.

I have a table like this one.

示例表

In which I have a sales table. From the sales table I need to get the sum of the transactions of one category within a category. For example, for each category in category 2, I would like to get the top Category 1 and the sum of sales.

To get a table like this:

在此处输入图片说明

I can do it separate for each category but I can't get a table with all of them.

Thanks!

One can use ROW_NUMBER or DENSE_RANK also over a SUM.

Then filter by that calculated number.

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

You know how to get the totals per category pair. Of these you want to show only the top rows per category2.

For this to happen you can rank the rows with RANK OVER , thus giving the top rows rank 1. In order to get the top rows only, you'd use TOP . Here you need the WITH TIES clause, because there are several rows with the same rank 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM