我有一张桌子
create table abc (id integer, value varchar(20), date1 date);
数据是:
insert into abc values (1 , a, '2015-02-01');
insert into abc values (1 , b, '2015-02-02');
insert into abc values (1 , c, '2015-02-03');
我想要的结果如下:
old value || new value || updated date
a || b || 2015-02-02
b || c || 2015-02-03
我如何得到这个结果?
答案 0 :(得分:0)
子选择和内连接的组合
SELECT
old.value as "old value",
new.value as "new value",
new.date1 as "updated date"
FROM abc AS OLD
INNER JOIN abc as new
WHERE old.id = new.id
AND new.date1 = (
SELECT MIN(date1) FROM abc
WHERE old.id = id
AND date1 > old.date1
)
答案 1 :(得分:0)
DB2的OLAP功能可以在这里提供帮助:
select id,
lag(value) over (partition by id order by date1) as "old value",
value as "new value",
date1 as "updated date"
from abc
我认为你可能还需要返回id列作为另一个id,你只需要它的旧值和新值。 此查询还将返回另外的第一行,这也可能有用。如果您想避免它(如您所示的示例中),请使用以下SQL
with temp as (
select id,
lag(value) over (partition by id order by date1) as "old value",
value as "new value",
date1 as "updated date"
from abc)
select * from temp
where "old value" is not null