SQL中上一行减去当前行

SQL中上一行减去当前行,sql,oracle,plsql,oracle-apex,Sql,Oracle,Plsql,Oracle Apex,我有一张点菜的桌子 如何为传入列减去上一行减去当前行 在我的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中使用函数 请尝试此查询 SELECT DATE_IN,Incoming, LAG(Incoming, 1, 0) O

我有一张点菜的桌子

如何为传入列减去上一行减去当前行

在我的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中使用函数

请尝试此查询

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

上一行定义了什么?日期对于给定的样本数据,您的预期结果是什么?它是用于mysql还是oracle?试着使用lead oracle函数:Hi Abhik,我需要它作为列输入为什么使用PL/SQL标记?是否需要存储过程?按传入的顺序不正确。将前一行减去当前行,而不是请求下一行的差值。所以我认为,正确的方向,错误的答案-谢谢你是个救生员。我一直在努力解决这个问题
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)
;