昨天的需求貌似不对啊.
要是计算变化率的话
应该是
10月1日和10月2日比,然后是10月2日和10月3日比.
昨天那个理解成了
10月1日和10月2日比,10月3日和10月4日比.
如果是
10月1日和10月2日比,然后是10月2日和10月3日比.
其实SQL还要简单一些.
数据同前文.
http://blog.itpub.net/29254281/viewspace-2127080/
SQL

-
select
-
case when id=1 then pk when id=2 then k when id=3 then '变化率' end k,
-
case when id=1 then pv1 when id=2 then v1 when id=3 then pv1-v1/pv1 end r1,
-
case when id=1 then pv2 when id=2 then v2 when id=3 then pv2-v2/pv2 end r2
-
from nums n ,
-
(
-
select
-
t1.k,
-
t1.k-1 pk,
-
t1.v1,
-
t1.v2,
-
round(@v1,4) as pv1,
-
round(@v2,4) as pv2,
-
round(@v1-v1/@v1,4) r1,
-
round(@v2-v2/@v2,4) r2,
-
@v1:=t1.v1 ,
-
@v2:=t1.v2 ,
-
@a:=@a+1 rn
-
from
-
(select @a:=0,@v1:=null, @v2:=null,@r1:=null,@r2:=null) var ,t t1
-
order by k
-
) a where n.id<=3 and a.rn!=1;
如果要间隔几天
比如间隔一天.改造也是容易的.

-
select
-
case when id=1 then k when id=2 then pk when id=3 then '变化率' end k,
-
case when id=1 then v1 when id=2 then pv1 when id=3 then r1 end r1,
-
case when id=1 then v2 when id=2 then pv2 when id=3 then r2 end r2
-
from nums n ,
-
(
-
select
-
t1.k,
-
t2.k pk,
-
t1.v1,
-
t1.v2,
-
t2.v1 as pv1,
-
t2.v2 as pv2,
-
round(t1.v1-t2.v1/t1.v1,4) r1,
-
round(t1.v2-t2.v2/t1.v2,4) r2
-
from
-
t t1
-
left join t t2 on (t1.k=t2.k-2)
-
where t2.k is not null
-
order by t1.k
-
) a where n.id<=3 ;
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-2127127/
,如需转载,请注明出处,否则将追究法律责任。