Re: Selecting latest value

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Patrik Kudo <kudo(at)partitur(dot)se>
Cc: Haller Christoph <ch(at)rodos(dot)fzk(dot)de>, pgsql-sql(at)postgresql(dot)org
Subject: Re: Selecting latest value
Date: 2001-09-20 15:07:35
Message-ID: 2678.1000998455@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Patrik Kudo <kudo(at)partitur(dot)se> writes:
> create table (userid text, val integer, ts timestamp);
> This table holds multiple values for users, timestamped for history
> reasons.
>
> Now I need to fetch the latest val for each userid to insert into a new
> table (with about the same schema, except for uniqueness on userid).
> I belive this should be a trivial task, but I'm experience total lack of
> insight here...

This is what SELECT DISTINCT ON was invented for. I don't know any
comparably easy way to do it in standard SQL, but with DISTINCT ON
it's not hard:

SELECT DISTINCT ON (userid) userid, val, ts FROM table
ORDER BY userid, ts DESC;

See the DISTINCT ON example in the SELECT reference page for more info:
http://www.ca.postgresql.org/users-lounge/docs/7.1/postgres/sql-select.html

regards, tom lane

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Patrik Kudo 2001-09-20 15:12:42 Re: Selecting latest value
Previous Message Stephan Szabo 2001-09-20 14:49:08 Re: Selecting latest value