我试图创建一个名为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的差异。
-------------------------------
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最后一行为2的Diff,因为对于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。
谢谢
发布于 2020-09-30 19:06:51
假设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 rephttps://stackoverflow.com/questions/64143908
复制相似问题