分享

SQLserver 相邻记录相减

 知足常乐WQL 2007-04-06

 


组       A             B         C  
    1         a1           b1       c1          
    1         a2           b2       c2      
    1         a3           b3       c3  
    2         a4           b4       c4  
    2         a5           b5       c5  
    2         a6           b6       c6  
   
    如何得到   1组的   (a2-a1)*c1   +   (a3-a2)*c2   ,(b2-b1)*c1   +   (b3-b2)*c2  
    同样   如何得到   2组的   (a5-a4)*c4   +   (a6-a5)*c5   ,(b5-b4)*c4   +   (b6-b5)*c5  
   
    即得到每组相临记录记录相减乘前一记录的C字段值之和  
   
    最后结果形如:  
     
    组       A                 B          
    1         a1x           b1x                
    2         a2x           b2x             
       
回复
declare   @a   table   (id   int,a   int,b   int,c   int)  
  insert   @a   values(1,1,10,2)  
  insert   @a   values(1,2,11,3)  
  insert   @a   values(1,3,12,4)  
  insert   @a   values(2,4,13,5)  
  insert   @a   values(2,5,14,6)  
  insert   @a   values(2,6,15,7)  
   
  select   *,0   a1,0   a2   into   #temp   from   @a  
  declare   @t0   int,@t1   int,@t2   int,@t4   int  
  declare   @y0   int,@y1   int  
  update   #temp   set    
  @t1=case   when   @t2=id   then   (a-@t0)*@t4   else   0   end,@t0=a,a1=@t1,  
  @y1=case   when   @t2=id   then   (b-@y0)*@t4   else   0   end,@y0=b,@t2=id,@t4=c,a2=@y1  
   
   
  select   sum(a1)   a1,sum(a2)   a2   from   #temp   group   by   id  
  drop   table   #temp  


http://cache.baidu.com/c?word=sql%2C%CF%E0%3B%C1%D9%2C%BC%C7%C2%BC%2C%CF%E0%3B%BC%F5&url=http%3A//topic%2Ecsdn%2Enet/t/20030211/21/1418812%2Ehtml&p=9739c64ad5c65afe1ab3c471091691&user=baidu
 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多