How to handle a group query

From: Nigel Metheringham <Nigel(dot)Metheringham(at)dev(dot)intechnology(dot)co(dot)uk>
To: pgsql-novice(at)postgresql(dot)org
Subject: How to handle a group query
Date: 2004-11-04 17:34:03
Message-ID: 1099589643.679.22.camel@angua.localnet
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Apologies for a longish message, but I'm no SQL expert and am trying to
get my head round some concepts.

What I am trying to do is get a set of rows out of a table based on a
set of grouping constraints. A simplified form of the table I am using
is:-
CREATE TABLE grouptest (
rowid serial PRIMARY KEY,
grouping integer,
tstval integer,
other character varying);

I want to get out rows of data where tstval is at a minimum value for
each set GROUPed by grouping. If there is more than one row with the
same minimal value for tstval then I want any of those rows (but the
data for a row must be consistent).

I got a way of doing this, but it has *three* nested selects - so it
feels that I am going to be really hammering the database as the table
gets big (need to start considering carefully where indexes should be on
this).

The query I came up with is (wait for it):-
SELECT * FROM grouptest JOIN
(SELECT MIN(rowid) AS rowid FROM grouptest AS second JOIN
(SELECT grouping,MIN(tstval) AS minval FROM grouptest
GROUP BY grouping)
AS first
ON (first.grouping = second.grouping
AND second.tstval = first.minval)
GROUP BY first.grouping)
AS third USING (rowid);

It seems that one alternative way of doing this would be to use a user
defined aggregate function, such that
MYMIN(rowid,tstval)
returns (one of) the rowid for which tstval was smallest.

This would remove the requirement for one of the nested SELECTs - and
make it much more readable.

Does this seem reasonable, and has anyone a simple example of an
aggregate function like this which I could build on.

Cheers
Nigel.
--
[ Nigel Metheringham Nigel(dot)Metheringham(at)InTechnology(dot)co(dot)uk ]
[ - Comments in this message are my own and not ITO opinion/policy - ]

Responses

Browse pgsql-novice by date

  From Date Subject
Next Message Tom Lane 2004-11-04 19:15:19 Re: How to handle a group query
Previous Message Aleksandar Dezelin 2004-11-04 15:47:31 Changing fileds of all database tables