pgsql-sql-owner@postgresql.org wrote:
> Hi,
>
> I'm trying to find out how to transform this kind of table data
> (history of rental data in a firm):
...
I have answred my own question: yes, there is a pure SQL solution, with
a subselect:
CREATE TABLE foo ( serial integer, delivery character(1), date integer
);
INSERT INTO foo (serial, delivery, date) VALUES (1, 'L', 1);
INSERT INTO foo (serial, delivery, date) VALUES (2, 'L', 1);
INSERT INTO foo (serial, delivery, date) VALUES (3, 'L', 1);
INSERT INTO foo (serial, delivery, date) VALUES (1, 'R', 2);
INSERT INTO foo (serial, delivery, date) VALUES (2, 'R', 2);
INSERT INTO foo (serial, delivery, date) VALUES (4, 'L', 2);
INSERT INTO foo (serial, delivery, date) VALUES (5, 'L', 3);
INSERT INTO foo (serial, delivery, date) VALUES (3, 'R', 3);
INSERT INTO foo (serial, delivery, date) VALUES (4, 'R', 3);
INSERT INTO foo (serial, delivery, date) VALUES (1, 'L', 4);
-------------
select
f.serial,
f.date as dateL,
( select f2.date from foo as f2 where f2.serial = f.serial and f2.date > f.date and f2.delivery = 'R' order by
f2.dateasc limit 1
) as dateR
from foo as f
where f.delivery = 'L'
order by f.serial, f.date
-------------
I'm not sure if we could use a self-join here...
Cheers,
Philippe Lang