Top N within groups? - Mailing list pgsql-general

From Klint Gore
Subject Top N within groups?
Date
Msg-id 4876D26C.1070202@une.edu.au
Whole thread Raw
In response to {SOLVED?] Re: functional index not used, looping simpler query just faster  (Ivan Sergio Borgonovo <mail@webthatworks.it>)
Responses Re: Top N within groups?
Re: Top N within groups?
how to found a variable is in a aggregation or not?
List pgsql-general
[was {SOLVED?] Re: [GENERAL] functional index not used, looping simpler
query just faster]
Ivan Sergio Borgonovo wrote:
> I'm still curious to know if this could be done
> efficiently with just one query.
>
[thinking out loud]
Can someone familiar with the source for DISTINCT ON comment on how hard
it would be to add another parameter to return more than one row?

e.g.
To do TOP 1 within an unknown number of groups
   select distinct on (groupid) groupid, identifier, count(*)
   from somequery
   group by groupid, identifier
   order by 1,3 desc,2;

I'm thinking that, for the top 3 within each group, something like
   select distinct on (groupid) FOR 3 groupid, identifier, count(*)
   from somequery
   group by groupid, identifier
   order by 1,3 desc,2;

For Ivan's case, groupid = brand, identifer = item. The where clause
applies the date limits.

klint.

--
Klint Gore
Database Manager
Sheep CRC
A.G.B.U.
University of New England
Armidale NSW 2350

Ph: 02 6773 3789
Fax: 02 6773 3266
EMail: kgore4@une.edu.au


pgsql-general by date:

Previous
From: "Gregory Williamson"
Date:
Subject: Re: storing latitude and longitude
Next
From: Devrim GÜNDÜZ
Date:
Subject: A better error message for reject option in pg_hba.conf