如何从前一行结果中减去?

时间:2015-01-12 09:59:36

标签: sql postgresql window-functions

我需要从lot_size + substraction result列中减去第一行currentitems。如果没有余额则应为0. bal是结果列的外观。

    rowno | location | lot_size | currentitems |  bal   | bal_left  
   -------+----------+----------+--------------+--------+--------
        1 | AB1210   |     1200 |         1000 |   1000 |   200
        2 | AB1220   |     1200 |         1000 |    200 |     0
        3 | AB1230   |     1200 |          500 |      0 |     0

当前的方法(使用postgresql 9.3.1):

SELECT 
    row_number() over (ORDER BY location) as rowno, 
    location,
    currentitems,
    1200 as lot_size,
    --here should be some case or something
    COALESCE(lag(currentitems) over(ORDER BY location),currentitems) AS bal
FROM foo;

1 个答案:

答案 0 :(得分:0)

不确定这是不是您要问的问题,但在这里您将如何获得下一行:

create table a(
  id bigserial primary key,
  val integer
);

select 
  nth_value(val,(row_nr+1)::integer) over () as next_value, 
  val, from 
      (select row_number() over () as row_nr, val from a) t;

然后你可以做你的案例和减法