Re: Complicated "group by" question

From: Jeff Boes <jboes(at)qtm(dot)net>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: Complicated "group by" question
Date: 2004-09-02 14:39:36
Message-ID: IgGZc.92877$JG7.85347@hydra.nntpserver.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Andrew Perrin wrote:
> I have a table of people ("reviewers"), a table of review assignments
> ("assign"), and a table of review acceptances ("accept"). I would like to
> be able to write a query to return the latest (e.g., max(assign_date))
> assignment for each reviewer, plus the acc_id field from "accept". I
> think I should be able to do this with a GROUP BY clause, but am having no
> luck.
>
> Table structure:
>
> reviewers assign accept
> -----------------------------------------
> reviewer_id assign_id accept_id
> reviewer_id assign_id
> ... assign_date
> ... ...
>

I think you want to write a non-GROUPed query using "DISTINCT ON".
Something like this:

SELECT DISTINCT ON (reviewer_id,assign_id)
reviewer_id,
assign_id,
assign_date,
accept_id
FROM reviewers
JOIN assign USING (reviewer_id)
JOIN accept USING (accept_id)
ORDER BY reviewer_id, assign_id, assign_date DESC;

--
(Posted from an account used as a SPAM dump. If you really want to get
in touch with me, dump the 'jboes' and substitute 'mur'.)
________
Jeffery Boes <>< jboes(at)qtm(dot)net

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Devrim GUNDUZ 2004-09-02 14:48:35 Re: PRIMARY KEY and INDEX
Previous Message Bruno Wolff III 2004-09-02 13:51:08 Re: copy old column's values to new column