在 SQL 中减去前一行减去当前行

Subtracting previous row minus current row in SQL

我有一个 table orders.

如何减去列 Incoming 的前一行减去当前行?

在我的 SQL

 select a.Incoming, 
coalesce(a.Incoming - 
    (select b.Incoming from orders b where b.id = a.id + 1), a.Incoming) as differance
from orders a

在 Oracle 中使用 LAG 函数。

试试这个查询

SELECT DATE_IN,Incoming,
   LAG(Incoming, 1, 0) OVER (ORDER BY Incoming) AS inc_previous,
   LAG(Incoming, 1, 0) OVER (ORDER BY Incoming) - Incoming AS Diff
FROM orders

SQL Fiddle Link

create table orders (date_in date, incoming_vol number);

insert into orders values (to_date('27.05.2015', 'DD.MM.YYYY'), 83);
insert into orders values (to_date('26.05.2015', 'DD.MM.YYYY'), 107);
insert into orders values (to_date('25.05.2015', 'DD.MM.YYYY'), 20);
insert into orders values (to_date('24.05.2015', 'DD.MM.YYYY'), 7);
insert into orders values (to_date('22.05.2015', 'DD.MM.YYYY'), 71);

LAG 函数用于访问前一行的数据

SELECT DATE_IN,
       incoming_vol as incoming,
       LAG(incoming_vol, 1, incoming_vol) OVER (ORDER BY date_in) - incoming_vol AS incoming_diff
FROM orders
order by 1 desc

另一种没有解析函数的解法:

select o.date_in, o.incoming_vol, p.incoming_vol-o.incoming_vol
from orders p, orders o
where p.date_in = (select nvl(max(oo.date_in), o.date_in) 
                   from orders oo where oo.date_in < o.date_in)
;