lets say I have a table like this:
| company | investor |
|---|---|
| apple | john |
| apple | john |
| apple | john |
| apple | alex |
| max | |
| max | |
| 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 |
| max | 2 |
obviously my example is stupid, but in terms of data and expected result it fully represents my concerns.
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