Re: Top 3 values for each group in PGSQL

From: Thomas Kellerer <spam_eater(at)gmx(dot)net>
To: pgsql-sql(at)lists(dot)postgresql(dot)org
Subject: Re: Top 3 values for each group in PGSQL
Date: 2019-03-01 12:52:02
Message-ID: 50d9b39f-56f8-8bc8-a93a-d5feb16f4dd3@gmx.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Ila B. schrieb am 01.03.2019 um 11:51:
> Hello,
>
> I’m working on a health database and I’m trying to extract the most popular prescription codes from a custom table I structured like this:
>
> Year - Code - Count(code)
>
> I want to extract the 3 codes with maximum count for each year. I know I should be using rank() but I don’t really understand how this works.
> I am using pgAdmin4 version 3.5 with PostgreSQL 10.6 on Windows 10 Pro and no permission to update.

Something along the lines:

select code, year, "count"
from (
select code, year, "count",
dense_rank() over (partition by code, year order by "count" desc) as rnk
from the_table
) t
where rnk <= 3;

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Rocky Ji 2019-03-01 12:55:44 Why does GROUP BY reduce number of rows?
Previous Message hubert depesz lubaczewski 2019-03-01 11:59:11 Re: Top 3 values for each group in PGSQL