dbTalk Databases Forums  

[SQL] Select every first/last record of a partition?

mailing.database.pgsql-sql mailing.database.pgsql-sql


Discuss [SQL] Select every first/last record of a partition? in the mailing.database.pgsql-sql forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
Andreas
 
Posts: n/a

Default [SQL] Select every first/last record of a partition? - 05-21-2012 , 11:04 AM






Hi,

suppose a table that has records with some ID and a timestamp.

id, ts
3, 2012/01/03
5, 2012/01/05
7, 2012/01/07
3, 2012/02/03
3, 2012/01/05
5, 2012/03/01
7, 2012/04/04

to fetch every last row of those IDs I do:

select id, ts
from ( select id, ts, row_number() over ( partition by id order
by ts desc ) as nr from mytab ) as x
where nr = 1


Is there a another way without a subselect?
There might be more columns so the window-functions first/last won't help.




--
Sent via pgsql-sql mailing list (pgsql-sql (AT) postgresql (DOT) org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-sql

Reply With Quote
  #2  
Old   
Seth Gordon
 
Posts: n/a

Default Re: [SQL] Select every first/last record of a partition? - 05-21-2012 , 04:17 PM






I think this would work:

select distinct on (id) id, ts --and whatever other columns you want
from mytab
order by id, timestamp desc;

On Mon, May 21, 2012 at 12:04 PM, Andreas <maps.on (AT) gmx (DOT) net> wrote:
Quote:
Hi,

suppose a table that has records with some ID and a timestamp.

id, Â* Â*ts
3, Â* Â*2012/01/03
5, Â* Â*2012/01/05
7, Â* Â*2012/01/07
3, Â* Â*2012/02/03
3, Â* Â*2012/01/05
5, Â* Â*2012/03/01
7, Â* Â*2012/04/04

to fetch every last row of those IDs I do:

select Â* id, ts
from Â* ( Â* select Â* id, ts, row_number() over ( partition by id Â* order by
ts desc ) as nr from mytab ) as x
where nr = 1


Is there a another way without a subselect?
There might be more columns so the window-functions first/last won't help.




--
Sent via pgsql-sql mailing list (pgsql-sql (AT) postgresql (DOT) org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-sql
--
Sent via pgsql-sql mailing list (pgsql-sql (AT) postgresql (DOT) org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-sql

Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.