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

Difference between rows of the same column if particular conditions are met

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

我的 table 看起来如下:

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

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

-------------------------------
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 为 2,因为 security_ID 2256 的计算结果为 5-3(分别针对 Date 202003 和 202002)。

编辑:因为 Sybase 没有 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 

但这并没有给我正确的答案。例如,根据上面的 Diff ,最后和倒数第二行的差异为 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

的查询尝试

如果你可以像你展示的那样使用window函数,你可以修改查询如下,

select security_id
     , dt
     , rep
     , (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