From: | "A(dot) Kretschmer" <andreas(dot)kretschmer(at)schollglas(dot)com> |
---|---|
To: | pgsql-novice(at)postgresql(dot)org |
Subject: | Re: Select only active entries |
Date: | 2010-07-21 06:59:48 |
Message-ID: | 20100721065948.GA20566@a-kretschmer.de |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | 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_select group 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
From | Date | Subject | |
---|---|---|---|
Next Message | Jayadevan M | 2010-07-21 09:16:54 | SELECT counts |
Previous Message | Carel Combrink | 2010-07-21 06:27:16 | Re: Select only active entries |