如果满足特定条件,则同一列的行之间的差异

问题描述

我正在尝试创建一个名为Diff的新列,该列包含名为Rep的同一列的不同行之间的差异,这是一个整数。

我的表如下所示:

------------------------
security_ID | Date | Rep 
------------------------
2256        |202001|  0
2257        |202002|  1
2258        |202003|  2
2256        |202002|  3
2256        |202003|  5

对于特定的security_ID,如果Rep(它们是整数)相差1(例如202002-202001 = 1)。例如,我希望输出为:

Date

最后一行是2的------------------------------- security_ID | Date | Rep | Diff ------------------------------- 2256 |202001| 0 | 0 2257 |202002| 1 | 1 2258 |202003| 2 | 2 2256 |202002| 3 | 3 2256 |202003| 5 | 2 ,因为对于Diff 2256,计算将为5-3(分别用于Date 202003和202002)。

编辑:因为Sybase没有security_ID,所以我尝试了以下操作:

LAG()

但这不能给我正确的答案。例如,根据以上所述,SELECT security_ID,Date,Rep,MIN(Rep) OVER (PARTITION BY Date,security_ID rows between current row and 1 following) - Rep as "Diff" from my_table 上方的最后一行和倒数第二行的差异为0。

谢谢

解决方法

假设date列始终按升序排列,我们可以将left join与self一起使用,并带出先前的rep值,然后在外面计算差值。

select security_id,dt,rep,(rep-prev_rep) diff
  from
(
select t1.security_id,t1.dt,t1.rep,coalesce(t2.rep,0) prev_rep
  from mytable t1
  left join mytable t2
    on t1.security_id = t2.security_id
   and t2.dt = t1.dt - 1
)
order by rep;

编辑:解决OP的查询尝试

如果您可以使用显示的窗口功能,则可以按如下所示修改查询,

select security_id,(rep-coalesce(max(rep) over (partition by security_id order by dt rows between unbounded preceding and 1 preceding),0)) diff
from mytable;
order by rep