Received: from localhost (maia-2.hub.org [200.46.204.187]) by postgresql.org (Postfix) with ESMTP id F22249F95B4 for ; Tue, 28 Aug 2007 13:10:21 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.187]) (amavisd-maia, port 10024) with ESMTP id 63984-04 for ; Tue, 28 Aug 2007 13:10:18 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.5 Received: from bach.incentre.net (bach.incentre.net [198.161.96.4]) by postgresql.org (Postfix) with ESMTP id 6E2339F97D0 for ; Tue, 28 Aug 2007 13:10:18 -0300 (ADT) Received: from sigurd.incentre.net (sigurd.incentre.net [206.75.213.195]) by bach.incentre.net (8.12.9p2/8.12.9) with ESMTP id l7SGAI5j032561 for ; Tue, 28 Aug 2007 10:10:18 -0600 (MDT) (envelope-from guy@incentre.net) Subject: Was: fetch first rows of grouped data From: Guy Fraser To: pgsql-sql@postgresql.org Content-Type: text/plain Organization: The Internet Centre Date: Tue, 28 Aug 2007 10:05:03 -0600 Message-Id: <1188317103.8070.34.camel@sigurd.incentre.net> Mime-Version: 1.0 X-Mailer: Evolution 2.6.3 (2.6.3-2.fc5) Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200708/247 X-Sequence-Number: 29185 Hi there I have a list of events that take place in a certain city at a certain date. Now I would like to have the first two (ordered by date) events for each city. Is there a way to do this with one query? I am using PostgreSQL 7.4. Thanks for any tips. Claudia I think I may have come up with a possible solution. Create a selection that produces a unique identifier for each city ordered by date then use array_accum to collect the unique identifiers for each city, then match the first two elements of the array with the identifiers. For instance if you had a table : CREATE TABLE crazy_talk ( ct_id bigserial primary key, ct_city text, ct_date date, ct_data text ) ; Then you could use : SELECT ct_id , ct_city , ct_date , ct_data FROM crazy_talk , (SELECT ct_city AS city, array_accum(ct_id) as match FROM crazy_talk ORDER BY ct_city , ct_date GROUP BY ct_city ) AS data_set WHERE ct_city = city AND ct_id IN (match[0],match[1]) ORDER BY ct_city , ct_date ; I hope this helps, I did not try it, but I think it should work. PS if you don't have array_accum here it is : CREATE AGGREGATE array_accum ( BASETYPE = anyelement, SFUNC = array_append, STYPE = anyarray, INITCOND = '{}' );