Re: Issues with lag command

From: Harald Fuchs <hari(dot)fuchs(at)gmail(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: Issues with lag command
Date: 2017-07-29 08:05:52
Message-ID: 87r2wzacrj.fsf@protecting.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Igor Neyman <ineyman(at)perceptron(dot)com> writes:

> Hello
> I have a test table with the following structure (2 columns: ID and time_id )and data
>
> ID, time_id
> 1;"2015-01-01"
> 2;""
> 3;""
> 4;"2015-01-02"
> 5;""
> 6;""
> 7;""
> 8;"2015-01-03"
> 9;""
> 10;""
> 11;""
> 12;""
> 13;"2015-01-05"
> 14;""
> 15;""
> 16;""
> I'd like to update line 2 and 3 with the date in record 1 (2015-01-01)
> Update line 5,6 and 7 with the date in record 4 (2015-01-02) and so on
> How about simple SQL instead of PlSql:
>
> UPDATE test T1 SET time_id = (SELECT T2.time_id FROM test T2 WHERE T2.id =
> (SELECT max(T3.id) FROM test T3 WHERE T3.id < T1.id AND T3.time_id IS NOT NULL)
> )
> WHERE T1.time_id IS NULL;

You don't need that many table aliases:

UPDATE test
SET time_id =
( SELECT T1.time_id
FROM test T1
WHERE T1.id < test.id
AND T1.time_id IS NOT NULL
ORDER BY T1.id DESC
LIMIT 1
)
WHERE time_id IS NULL;

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message srilinux 2017-07-29 17:38:25 Re: created database but access is not copied ? any suggestions
Previous Message David G. Johnston 2017-07-28 23:00:02 Re: created database but access is not copied ? any suggestions