Re: querying the value of the previous row

From: "A(dot) Kretschmer" <andreas(dot)kretschmer(at)schollglas(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: querying the value of the previous row
Date: 2010-03-12 06:13:35
Message-ID: 20100312061335.GA27286@a-kretschmer.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

In response to Chris Velevitch :
> I'm to write a query like:-
>
> select
>      case when column_name1 <> value_of_previous(column_name1)
>           then column_name1 end as column
>     ,column_name2
> from table
> ordered by column_name1, column_name2

Okay, with this table:

test=# select * from foo;
col1 | col2
------+------
1 | 1
1 | 2
1 | 3
2 | 4
2 | 5
2 | 6
2 | 7
3 | 8
4 | 9
5 | 10
(10 rows)

you can do:

test=# select
case when col1::text <> coalesce(lag::text,'NULL') then col1 else null end as col1,
col2
from (
select col1, lag(col1) over (range unbounded preceding ),
col2
from foo
order by col2
) foo order by col2;
col1 | col2
------+------
1 | 1
| 2
| 3
2 | 4
| 5
| 6
| 7
3 | 8
4 | 9
5 | 10
(10 rows)

>
> How do I do this? (I'm using pg 7.4)

Unfortunately (for you), i'm using a window-function, in this case
lag(), new since 8.4. Your version 7.4 has reached End-of-Lifetime, so
i suggest you update to 8.4.

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

In response to

Browse pgsql-general by date

  From Date Subject
Next Message John R Pierce 2010-03-12 06:14:37 Re: querying the value of the previous row
Previous Message Chris Velevitch 2010-03-12 04:51:26 querying the value of the previous row