Problem with aggregate functions and GROUP BY

From: "Alex Page" <alex(dot)page(at)solid-state-logic(dot)com>
To: <pgsql-sql(at)postgresql(dot)org>
Subject: Problem with aggregate functions and GROUP BY
Date: 2001-08-08 16:16:24
Message-ID: 02ac01c12025$78644300$7fc472c1@solidstatelogic.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

I'm having real trouble with aggregate functions. I have a table which
tracks the value of a field in another table over time - it contains a
foreign key to the row in the other table, the value, and a timestamp to
sort by. I'm trying to write a query that returns the rows containing the
most recent values for each foreign key.

The table looks like this: (fixed width fonts required, and this is a test
table):

# SELECT * FROM test ORDER BY fk, sortby;
fk | value | sortby
----+-------+--------
1 | 2 | 1
1 | 0 | 2
1 | 4 | 3
2 | 2 | 1

Now obviously, what I'm aiming for is:

fk | value | sortby
----+-------+--------
1 | 4 | 3
2 | 2 | 1

which is the highest value of 'sortby' for each value of 'fk'.

I would think that the SQL to achieve this is:

SELECT * FROM test GROUP BY fk HAVING sortby = MAX(sortby);

but running this in psql gives:

ERROR: Attribute test.value must be GROUPed or used in an aggregate
function

No matter what I do to the query, it gives me this message for test.value
and test.sortby, unless I GROUP BY all three of them, which doesn't give me
the result I want. I'm completely stumped - can anyone help?

Thanks in advance,

Alex
--
Alex Page, IT Department, Solid State Logic
E-Mail: alex(dot)page(at)solid-state-logic(dot)com
Phone: +44 (0) 1865 842 300
Web: http://www.solid-state-logic.com

**********************************************************************
This email and any files transmitted with it are confidential and
intended solely for the use of the individual or entity to whom they
are addressed. If you have received this email in error please notify
the system manager.

This footnote also confirms that this email message has been swept by
MIMEsweeper for the presence of computer viruses.

www.mimesweeper.com
**********************************************************************

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Josh Berkus 2001-08-08 16:26:56 Re: Functions returning more than one value
Previous Message Jeff Eckermann 2001-08-08 16:08:14 RE: RE: Referencing named attribute in where clause doesn't work with7.1.2?