简体   繁体   中英

In PostgreSQL, how to select the previous row value to compute the current row value?

I am looking for a PostgreSQL query where I want to compute the current row value based on the previous row value. Below is the table for example, the value1 column will have the first initial value and then I need to compute the rows after using the previous row value.

The formula for value1 column in the current row would be previous value1 + the current row's id .

Table:

在此处输入图片说明

Desired output :

在此处输入图片说明

This will do it. It's not especially efficient though, but for a one off it should do.

select x.id, sum(coalesce(y.value1,y.id,0))
from sample x
left outer join sample y on x.id >= y.id
group by x.id
order by x.id

Basically, it goes through every record in the table, and then sums up the IDs of all the records up to and including that record. There is a special logic to handle the initial value you've got on id=1.

SQL Fiddle at http://sqlfiddle.com/#!9/b8f25/1

Another option is to use a window function.

select x.id, sum(coalesce(x.value1,x.id,0)) over (order by x.id)
from sample x

SQL Fiddle at http://sqlfiddle.com/#!17/b8f25/2

You can do this with a recursive query:

with recursive prev_row as (
    select id, value1
    from my_table
    where id = 1
union all
    select t.id, p.value1+ t.id
    from prev_row p
    join my_table t on t.id = p.id+ 1
)
select id, value1
from prev_row

Db<>fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM