Re: Group by and lmit

From: Filip Rembiałkowski <filip(dot)rembialkowski(at)gmail(dot)com>
To: Bill Reynolds <Bill(dot)Reynolds(at)ateb(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Group by and lmit
Date: 2010-11-04 00:07:00
Message-ID: AANLkTikz7yGrQ5e-zo-fGqhWn_B4OG5Lc0aWPpHrmTeC@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

2010/11/2 Bill Reynolds <Bill(dot)Reynolds(at)ateb(dot)com>:
>    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(dot)rembialkowski(at)gmail(dot)com
http://filip.rembialkowski.net/

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Joseph Conway 2010-11-04 00:16:21 Re: Problem with Crosstab (Concatenate Problem)
Previous Message Igor Neyman 2010-11-03 20:15:45 Re: Return key from query