不需要循环,甚至不需要存储这些数据。显然,您需要“速度”列的“运行总和”,这可以使用窗口函数轻松完成:
(从Depesz的答案中无耻地窃取样本数据)
create table whatever
(
time_c int4,
speed int4,
distance int8
);
insert into whatever (time_c, speed)
values
( 1,53),
( 2,17),
( 3,53),
( 4,46),
( 5,31),
( 6,18),
( 7,42),
( 8,15),
( 9, 1),
(10,51);
select time_c,
speed,
sum(speed) over (order by time_c) as distance
from whatever
order by time_c;
时间_c | 速度 | 距离
--------+-------+---------
1 | 53 | 53
2 | 17 | 70
3 | 53 | 123
4 | 46 | 169
5 | 31 | 200
6 | 18 | 218
7 | 42 | 260
8 | 15 | 275
9 | 1 | 276
10 | 51 | 327
如果您真的想要存储可以轻松计算的数据,您可以使用单个更新语句来做到这一点:
with derived_data as (
select time_c,
speed,
sum(speed) over (order by time_c) as distance
from whatever
)
update whatever
set distance = dd.distance
from derived_data dd
where dd.time_c = whatever.time_c;
此更新假定这time_c
是表中的唯一属性。
SQLFiddle 示例:http ://sqlfiddle.com/#!12/16332/2