pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: Patrik Kudo <kudo@partitur.se>
Cc: Haller Christoph <ch@rodos.fzk.de>
Cc: pgsql-sql@postgresql.org
Subject: Re: Selecting latest value
Date: Thu, 20 Sep 2001 11:07:35 -0400
Message-ID: <2678.1000998455@sss.pgh.pa.us> (raw)
In-Reply-To: <Pine.BSF.4.31.0109201555480.17720-100000@tb303.partitur.se>
References: <Pine.BSF.4.31.0109201555480.17720-100000@tb303.partitur.se>

Patrik Kudo <kudo@partitur.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



view thread (6+ messages)  latest in thread

Message-ID: <2678.1000998455@sss.pgh.pa.us>
Permalink:  ../2678.1000998455@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/2678.1000998455@sss.pgh.pa.us

 · 

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: tgl@sss.pgh.pa.us, kudo@partitur.se, ch@rodos.fzk.de
  Subject: Re: Selecting latest value
  In-Reply-To: <2678.1000998455@sss.pgh.pa.us>

* 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