Re: Am I crazy or is this SQL not possible

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Collin Peters" <cadiolis(at)gmail(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Am I crazy or is this SQL not possible
Date: 2006-06-01 19:21:31
Message-ID: 14505.1149189691@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

"Collin Peters" <cadiolis(at)gmail(dot)com> writes:
> What I would like to do is simply get the last date_sent and it's
> status for every broadcast. I can't do a GROUP BY because I can't put
> an aggregate on the status column.

You missed the key idea about how to use DISTINCT ON.

SELECT DISTINCT ON (email_broadcast_id) *
FROM email_broadcast_history
ORDER BY email_broadcast_id, date_sent DESC

You order by the DISTINCT ON fields, then one or more additional fields
to select the representative row you want within each DISTINCT ON group.

regards, tom lane

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Aaron Bono 2006-06-01 19:30:31 Re: Am I crazy or is this SQL not possible
Previous Message Florian Weimer 2006-06-01 18:59:05 Re: SELECT DISTINCT too slow