2010/11/2 Bill Reynolds <Bill.Reynolds@xxxxxxxx>: > ÂÂ Iâm using postgres 8.3.7. that's a pity because in 8.4 we have window functions which make this possible in one query: select * from ( select x, y, count(*) as counter, row_number() over(partition by x order by count(*)) rn from mytable group by x, y order by x, count(*), y ) subq where subq.rn <= 5; in 8,3 you will have to use some tricks... for example, temporary sequence for every group. CREATE LANGUAGE plpgsql; create or replace function exec(text) returns text as 'begin execute $1;return $1;end' language plpgsql; select exec('create temp sequence tmpseq'||x) from (select distinct x from mytable) q; select x,y,counter from (select x, y, count(*) as counter from mytable group by x, y order by x, counter, y) subq where nextval(quote_ident('tmpseq'||x))<=5; -- Filip RembiaÅkowski JID,mailto:filip.rembialkowski@xxxxxxxxx http://filip.rembialkowski.net/ -- Sent via pgsql-general mailing list (pgsql-general@xxxxxxxxxxxxxx) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-general