ITPub博客

首页 > 数据库 > MySQL > 隔两行生一行计算变化率(续)

隔两行生一行计算变化率(续)

原创 MySQL 作者:壹頁書 时间:2016-10-26 10:32:23 0 删除 编辑
昨天的需求貌似不对啊.
要是计算变化率的话
应该是
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



  1. select    
  2. case when id=1 then pk when  id=2 then k when id=3 then '变化率' end k,  
  3. case when id=1 then pv1 when  id=2 then v1 when id=3 then pv1-v1/pv1 end r1,  
  4. case when id=1 then pv2 when  id=2 then v2 when id=3 then pv2-v2/pv2 end r2  
  5. from nums n ,  
  6. (  
  7.         select     
  8.             t1.k,    
  9.             t1.k-1 pk,  
  10.             t1.v1,    
  11.             t1.v2,    
  12.             round(@v1,4) as pv1,    
  13.             round(@v2,4) as pv2,    
  14.             round(@v1-v1/@v1,4) r1,    
  15.             round(@v2-v2/@v2,4) r2,    
  16.             @v1:=t1.v1 ,    
  17.             @v2:=t1.v2 ,  
  18.             @a:=@a+1 rn  
  19.         from    
  20.             (select @a:=0,@v1:=null, @v2:=null,@r1:=null,@r2:=null) var ,t t1    
  21.         order by k     
  22. ) a where n.id<=3 and a.rn!=1; 


如果要间隔几天
比如间隔一天.改造也是容易的.



  1. select    
  2. case when id=1 then k when  id=2 then pk when id=3 then '变化率' end k,  
  3. case when id=1 then v1 when  id=2 then pv1 when id=3 then r1 end r1,  
  4. case when id=1 then v2 when  id=2 then pv2 when id=3 then r2 end r2  
  5. from nums n ,  
  6. (  
  7.         select     
  8.             t1.k,    
  9.             t2.k pk,  
  10.             t1.v1,    
  11.             t1.v2,    
  12.             t2.v1 as pv1,    
  13.             t2.v2 as pv2,    
  14.             round(t1.v1-t2.v1/t1.v1,4) r1,    
  15.             round(t1.v2-t2.v2/t1.v2,4) r2  
  16.         from    
  17.             t t1    
  18.         left join t t2 on (t1.k=t2.k-2)  
  19.         where t2.k is not null  
  20.         order by t1.k  
  21. ) a where n.id<=3 ; 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-2127127/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: 简易LruMap
请登录后发表评论 登录
全部评论

注册时间:2013-10-19

  • 博文量
    620
  • 访问量
    6339922