pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Julian Scarfe <julian@avbrief.com>
To: Alex <alex@meerkatsoft.com>
To: pgsql-general@postgresql.org
Subject: Re: SQL Question
Date: Sat, 16 Apr 2005 09:10:37 +0100
Message-ID: <004a01c5425b$c6b4c500$0600a8c0@Wilbur> (raw)
References: <425FAC67.2050203@meerkatsoft.com>

From: "Alex" <alex@meerkatsoft.com>

> - How can i select only the newest record for each ProdId ?
>
> 100    | 2005-04-01
> 200    | 2005-04-01
>

DISTINCT ON was made for this and on the similar tables I have performs 
rather more efficiently than using a subquery.

select distinct on (ProdId) ProdId , LastUpdate
from produpdate
order by ProdId , LastUpdate desc;

> - How can i select to retrieve the last 2 dates in record
>
> 100    | 2005-04-01 | 2005-03-01
> 200    | 2005-04-01 | 2005-03-01

To get the previous one, my first thought is something like:

select distinct on (ProdId) ProdId , LastUpdate
from produpdate p1
where LastUpdate <> (
    select max(LastUpdate ) from produpdate p2 where p2.ProdId = p1.ProdId
)
order by ProdId , LastUpdate desc ;

but there may be a much more efficient way of getting the nth result in 
general.

Julian Scarfe 





view thread (71+ messages)  latest in thread

Message-ID: <004a01c5425b$c6b4c500$0600a8c0@Wilbur>
Permalink:  ../004a01c5425b$c6b4c500$0600a8c0@Wilbur/
Also on:    postgresql.org/message-id/004a01c5425b$c6b4c500$0600a8c0@Wilbur

 · 

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 from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-general@postgresql.org
  Cc: julian@avbrief.com, alex@meerkatsoft.com
  Subject: Re: SQL Question
  In-Reply-To: <004a01c5425b$c6b4c500$0600a8c0@Wilbur>
  References: <425FAC67.2050203@meerkatsoft.com> <004a01c5425b$c6b4c500$0600a8c0@Wilbur>

* 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