pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Thomas Kellerer <spam_eater@gmx.net>
To: pgsql-sql@lists.postgresql.org
Subject: Re: Top 3 values for each group in PGSQL
Date: Fri, 1 Mar 2019 13:52:02 +0100
Message-ID: <50d9b39f-56f8-8bc8-a93a-d5feb16f4dd3@gmx.net> (raw)
In-Reply-To: <67FB61BF-CF8F-440E-B4C5-B6F72D61A9C7@gmail.com>
References: <67FB61BF-CF8F-440E-B4C5-B6F72D61A9C7@gmail.com>

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;





view thread (4+ messages)  latest in thread

Message-ID: <50d9b39f-56f8-8bc8-a93a-d5feb16f4dd3@gmx.net>
Permalink:  ../50d9b39f-56f8-8bc8-a93a-d5feb16f4dd3@gmx.net/
Also on:    postgresql.org/message-id/50d9b39f-56f8-8bc8-a93a-d5feb16f4dd3@gmx.net

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: spam_eater@gmx.net, pgsql-sql@lists.postgresql.org
  Subject: Re: Top 3 values for each group in PGSQL
  In-Reply-To: <50d9b39f-56f8-8bc8-a93a-d5feb16f4dd3@gmx.net>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox