From: | Kevin Grittner <kgrittn(at)ymail(dot)com> |
---|---|
To: | Paul Linehan <linehanp(at)tcd(dot)ie>, Ken Benson <Ken(at)infowerks(dot)com> |
Cc: | "pgsql-novice(at)postgresql(dot)org" <pgsql-novice(at)postgresql(dot)org> |
Subject: | Re: Help with a JOIN. |
Date: | 2014-07-23 20:05:12 |
Message-ID: | 1406145912.24536.YahooMailNeo@web122302.mail.ne1.yahoo.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-novice |
Paul Linehan <linehanp(at)tcd(dot)ie> wrote:
> I have two tables - ticket and comment (DDL and DML below) and I
> want to get the latest comment on a ticket which hasn't been
> modified for some arbitrary period (in this example, 2 years (60M
> seconds)).
A simple description like that, coupled with the DDL and data,
makes life really easy for someone to help. :-) Try this:
SELECT DISTINCT ON (t.ticket_id)
t.ticket_id,
t.ticket_description,
c.comments_timestamp AS c_max_date,
c.comments_comment
FROM ticket AS t
JOIN comment c ON c.ticket_id = t.ticket_id
WHERE c.comments_timestamp < extract(epoch FROM TIMESTAMP '2014-07-20') - 60000000
ORDER BY
t.ticket_id,
c.comments_timestamp DESC;
SELECT DISTINCT ON gives you one row for each distinct combination
of values in parentheses, and when there are duplicates it keeps
the first one based on the ORDER BY clause.
--
Kevin Grittner
EDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company
From | Date | Subject | |
---|---|---|---|
Next Message | Shreesha | 2014-07-29 17:18:30 | WAL for backup |
Previous Message | David G Johnston | 2014-07-23 18:24:10 | Re: Multiple foreign keys to the same table |