From: | Michael Glaesemann <grzm(at)seespotcode(dot)net> |
---|---|
To: | Kevin Jenkins <gameprogrammer(at)rakkar(dot)org> |
Cc: | pgsql-general(at)postgresql(dot)org |
Subject: | Re: SQL query question |
Date: | 2006-06-18 00:35:22 |
Message-ID: | 45F6FB15-3DD1-4E68-96C6-1DF74F02FC8F@seespotcode.net |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
On Jun 18, 2006, at 8:50 , Kevin Jenkins wrote:
> I have a beginner question. I have a table with a bunch of
> filenames and each of them have a date. Multiple files may have
> the same name. For example
>
> filename date revision
> file1 10/05/06 1
> file1 10/05/07 2
> file2 10/05/08 1
>
> I want to do a query that will return the greatest date for each
> unique filename
I can think of two ways to do this (and there are probably more): one
using standard SQL and one using PostgreSQL extensions. Here's the
standard SQL way:
SELECT filename, date, revision
FROM table_with_bunch_of_filenames
NATURAL JOIN (
SELECT filename, max(date) as date
FROM table_with_bunch_of_filenames
GROUP BY filename
) AS most_recent_dates;
If you don't need the revision, you can just use the subquery-- the
stuff in the
parentheses after NATURAL JOIN.
And here's the way using DISTINCT ON, which is a PostgreSQL extension.
SELECT DISTINCT ON (filename, date)
filename, date, revision
FROM table_with_bunch_of_filenames
ORDER BY filename, date desc;
Hope this helps.
Michael Glaesemann
grzm seespotcode net
From | Date | Subject | |
---|---|---|---|
Next Message | Bruno Wolff III | 2006-06-18 10:07:15 | Re: SQL query question |
Previous Message | Kevin Jenkins | 2006-06-17 23:50:59 | SQL query question |