Re: Select only active entries - Mailing list pgsql-novice

From A. Kretschmer
Subject Re: Select only active entries
Date
Msg-id 20100721065948.GA20566@a-kretschmer.de
Whole thread Raw
In response to Re: Select only active entries  ("Carel Combrink" <s25291930@tuks.co.za>)
List pgsql-novice
In response to Carel Combrink :
>
> They are not time stamped but in sequence. The latest active one is
> basically if  you look at number 5. It goes from active to inactive to
> active again at time of the query. I want to know if the last entry of
> ID 5 was active or inactive. And so-forth for all the rest of the
> ID's. So only select the IDs that were active on their last entry into
> the database.
>
> Is there a way of querying the data to obtain only the last entry in
> the table for a given ID?

There are no UPDATE or DELETE, just only INSERTs into the table?

If yes, maybe this should work for you:

test=*# select * from test_select;
 id | is_active
----+-----------
  5 | t
  5 | f
  6 | t
  7 | t
  8 | t
  5 | t
  8 | f
  9 | t
 10 | t
  6 | f
 10 | f
(11 rows)

test=*# select id, is_active from (select id, is_active, max(ctid), row_number() over (partition by id) from
test_selectgroup by id, is_active, ctid order by id, ctid desc) foo where is_active and row_number = 1; 
 id | is_active
----+-----------
  5 | t
  7 | t
  9 | t
(3 rows)


You *should* consider an additional column, timestamp for instance, the
trick with ctid isn't a clean solution.


Andreas
--
Andreas Kretschmer
Kontakt:  Heynitz: 035242/47150,   D1: 0160/7141639 (mehr: -> Header)
GnuPG: 0x31720C99, 1006 CCB4 A326 1D42 6431  2EB0 389D 1DC2 3172 0C99

pgsql-novice by date:

Previous
From: "Carel Combrink"
Date:
Subject: Re: Select only active entries
Next
From: Jayadevan M
Date:
Subject: SELECT counts