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 get top count of a column per group in sql (postgresql)

lets say I have a table like this:

company investor
apple john
apple john
apple john
apple alex
google max
google max
google oliver

I want to write a query that finds the top investor per company and get a response like this:

company investor count
apple john 3
google max 2

obviously my example is stupid, but in terms of data and expected result it fully represents my concerns.

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

UPDATED:

as mentioned by @jarlh if a company has more than one top investor then I would like to get the first one as sorted by name, like if we have one more row for google and oliver then I would want to get max and 2 because of the names being sorted alphabetically in result;

>Solution :

You can do this

with x as (
select rank() over (partition by company order by count(*) desc, investor) as rank, company,investor,count(*) as qty from test group by company,investor)
select * from x where rank = 1

in case of equality between 2 investors and you want to get both then run the query like this

with x as (
select rank() over (partition by company order by count(*) desc) as rank, company,investor,count(*) as qty from test group by company,investor)
select * from x where rank = 1

Result here

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