pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Josh Berkus <josh@agliodbs.com>
To: Andrew Perrin <clists@perrin.socsci.unc.edu>
To: pgsql-sql@postgresql.org
Subject: Re: Complicated "group by" question
Date: Wed, 25 Aug 2004 10:47:18 -0700
Message-ID: <200408251047.18645.josh@agliodbs.com> (raw)
In-Reply-To: <Pine.LNX.4.53.0408251300580.20106@perrin.socsci.unc.edu>
References: <Pine.LNX.4.53.0408251300580.20106@perrin.socsci.unc.edu>

Andrew,

> 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.

Some vagueness: you didn't say whether you wanted to see two assignments if 
they have the same, latest date.   Nor did you specify whether you wanted to 
see assignments that had not been accepted (the below assumes yes to both)

Hmmm ... one way, SQL-standard:

SELECT reviewer.name, assign_date, acc_id
FROM reviewers JOIN assign ON reviewer.id = assign.reviewer_id
	LEFT OUTER JOIN accept ON assign.id = accept.assign_id
WHERE assign_date IN (SELECT max(ass2.assign_date) FROM assign ass2
	WHERE ass2.reviewer_id = reviewers.id)

or for a bit faster execution on PG you cann replace that WHERE clause with:

WHERE assign_date IN (SELECT ass2.assign_date FROM assign ass2
	WHERE ass2.reviewer_id = reviewers.id ORDER BY ass2.assign_date DESC LIMIT 1)

-- 
Josh Berkus
Aglio Database Solutions
San Francisco



view thread (5+ messages)  latest in thread

Message-ID: <200408251047.18645.josh@agliodbs.com>
Permalink:  ../200408251047.18645.josh@agliodbs.com/
Also on:    postgresql.org/message-id/200408251047.18645.josh@agliodbs.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: josh@agliodbs.com, clists@perrin.socsci.unc.edu
  Subject: Re: Complicated "group by" question
  In-Reply-To: <200408251047.18645.josh@agliodbs.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox