Re: Group by and lmit - Mailing list pgsql-general

From Filip Rembiałkowski
Subject Re: Group by and lmit
Date
Msg-id AANLkTikz7yGrQ5e-zo-fGqhWn_B4OG5Lc0aWPpHrmTeC@mail.gmail.com
Whole thread Raw
In response to Group by and lmit  ("Bill Reynolds" <Bill.Reynolds@ateb.com>)
List pgsql-general
2010/11/2 Bill Reynolds <Bill.Reynolds@ateb.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.rembialkowski@gmail.com
http://filip.rembialkowski.net/

pgsql-general by date:

Previous
From: "Igor Neyman"
Date:
Subject: Re: Return key from query
Next
From: Joseph Conway
Date:
Subject: Re: Problem with Crosstab (Concatenate Problem)