【问题标题】:How to subtract from previous row result?如何从上一行结果中减去?
【发布时间】:2015-01-12 09:59:35
【问题描述】:

我需要从currentitems 列中减去第一行lot_size + substraction result。如果没有余额,则应为 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;

【问题讨论】:

  • 你当前的sql是什么样的?
  • lag() 仅使用上一行,而不是上一行结果

标签: sql postgresql window-functions


【解决方案1】:

不确定这是否是您要问的,但这是获得下一行的方法:

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;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多