Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort and limit an SQL table by sum of a numerical column grouped by multiple categories?

I have the following SQL table:

Country ProductID Price
US 1 10
US 2 20
GB 3 25
GB 4 40
US 1 10
US 1 10
DE 2 20
DE 2 20

I want to see the two most profitable (per sum of price) "ProductID" per "Country" (sorted by Sum per "Country") like this:

Country ProductID Sum
US 4 40
US 1 30
GB 4 40
GB 3 25
DE 2 20

How can I perform this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We can use RANK here in conjunction with an aggregation by country and product:

WITH cte AS (
    SELECT Country, ProductID, SUM(Price) AS Sum,
           RANK() OVER (PARTITION BY Country ORDER BY SUM(Price) DESC) rnk
    FROM yourTable
    GROUP BY Country, ProductID
)

SELECT Country, ProductID, Sum
FROM cte
WHERE rnk <= 2
ORDER BY Country, rnk;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading