简体   繁体   中英

Subtracting previous row minus current row in SQL

I have a table orders .

How do I subtract previous row minus current row for the column Incoming ?

在此输入图像描述

in My 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

Use LAG function in Oracle.

Try this query

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);

The LAG function is used to access data from a previous row

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

Another solution without analytical functions:

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)
;

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