[SQL] Issues with lag command
От | Mohamed DIA |
---|---|
Тема | [SQL] Issues with lag command |
Дата | |
Msg-id | CA+oNSn9i4PCRQKvwpGM3wRkWfMMSW6Mrc-9KsUdhWQceQFjcpA@mail.gmail.com обсуждение исходный текст |
Ответы |
Re: [SQL] Issues with lag command
Re: [SQL] Issues with lag command |
Список | pgsql-sql |
Hello
I have a test table with the following structure (2 columns: ID and time_id )and dataID, 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)2;""
3;""
4;"2015-01-02"
5;""
6;""
7;""
8;"2015-01-03"
9;""
10;""
11;""
12;""
13;"2015-01-05"
14;""
15;""
16;""
CREATE OR REPLACE FUNCTION public.update_test_dates()
RETURNS SETOF test AS
$BODY$
DECLARE
r test%rowtype;
BEGIN
FOR r IN SELECT * FROM test order by id
LOOP
-- can do some processing here
if r.time_id is null
then
update test set time_id= (select lag(time_id) OVER (ORDER BY id) from test where id=r.id) where id=r.id;
end if;
RETURN NEXT r; -- return current row of SELECT
END LOOP;
RETURN;
END
$BODY$
LANGUAGE plpgsql;
select * from update_test_dates();
В списке pgsql-sql по дате отправления: