数据需求:
从数据处理的层面,直接计算出指标的最新值与上次最新值的差值
从数据处理的层面,直接计算出指标的最新值与上次最新值的差值
如下图,计算出下列两行记录的差值
相关SQL:
--dif为差值字段
with tb as (
select t.*,t.columnvalue1-Lead(t.columnvalue1,1,0) over(order by t.gathertime desc) DIF
from z_getpassengertotal t
),
tb2 as (
select max(t.gathertime) gathertime
from tb t
where 1=1
)
select t.*
from tb t
where 1=1
and exists (select 1 from tb2 t2 where t.gathertime = t2.gathertime);
查询结果:
说明:
Lag和Lead分析函数可以在同一次查询中取出同一字段的前N行的数据(Lag)和后N行的数据(Lead)作为独立的列。
这种操作可以代替表的自联接,并且LAG和LEAD有更高的效率。
/*语法*/
lag(exp_str,offset,defval) over()
Lead(exp_str,offset,defval) over()
--exp_str要取的列
--offset取偏移后的第几行数据
--defval:没有符合条件的默认值