Re: Please help me write a query

From: Tim Landscheidt <tim(at)tim-landscheidt(dot)de>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: Please help me write a query
Date: 2010-05-27 15:57:08
Message-ID: m363291gob.fsf@passepartout.tim-landscheidt.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Nikolas Everett <nik9000(at)gmail(dot)com> wrote:

> Sorry. Here is the setup:
> CREATE TABLE test (id BIGSERIAL PRIMARY KEY, state1 INT NOT NULL, state2 INT
> NOT NULL, timestamp TIMESTAMP);
> INSERT INTO test (state1, state2, timestamp) VALUES (1, 1, now() - interval
> '12 hours');
> INSERT INTO test (state1, state2, timestamp) VALUES (1, 2, now() - interval
> '11 hours');
> INSERT INTO test (state1, state2, timestamp) VALUES (1, 1, now() - interval
> '10 hours');
> INSERT INTO test (state1, state2, timestamp) VALUES (2, 1, now() - interval
> '9 hours');
> INSERT INTO test (state1, state2, timestamp) VALUES (1, 1, now() - interval
> '8 hours');

> I want to write a query that spits out:
> state1 | timestamp
> --------+----------------------------
> 1 | now() - interval '12 hours'
> 2 | now() - interval '9 hours'
> 1 | now() - interval '8 hours'

> Standard grouping destroys the third row so that's out. No grouping at all
> gives repeats of state1. Is this what partitioning is for?

Partitioning usually means splitting data across several
tables for faster access which is probably not what you want
here.

A simple solution would be to use LAG() and discard rows
where the current value is equal to the preceding value:

| SELECT state1, timestamp
| FROM
| (SELECT id,
| state1,
| state2,
| LAG(state1) OVER (ORDER BY timestamp) AS prevstate1,
| timestamp FROM test) AS SubQuery
| WHERE state1 IS DISTINCT FROM prevstate1
| ORDER BY timestamp;

Tim

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Rainer Pruy 2010-05-27 16:12:39 UPDATE...RETURNING col INTO var - what is returned?
Previous Message erobles 2010-05-27 15:54:08 Re: hi, trying to compile postgres 8.3.11