上下两条记录比较的问题

table1   中   col1字段  
  每两条记录做一比较   如果差额大于10     累计该差额。  
  如:  
  id       col1  
  1             1  
  2             3  
  3             14  
  4             15                                     则累计为11   

 

 

 

--测试环境  
  declare   @t   table(id   int   identity(1,1),col1   int)  
  insert   into   @t   select   1  
  union   all   select   3  
  union   all   select   14  
  union   all   select   15  
   
  --查询语句  
  select   a.id,b.id,a.col1,b.col1,累计该差额=abs(a.col1-b.col1)  
  from   @t   A,@t   B  
  where   abs(a.col1-b.col1)>10  
  and   abs(a.id-b.id)=1  
  and   a.id<=b.id  
  --结果  
  id                     id                     col1                 col1                 累计该差额                
  -----------   -----------   -----------   -----------   -----------    
  2                       3                       3                       14                     11  
   
  (所影响的行数为   1   行)   

 

 

declare   @tb   table  
  (  
      id   int,  
      col   int  
  )  
  insert   @tb  
  select   1,1   union  
  select   2,3   union  
  select   3,14   union  
  select   4,15  
   
  --查询  
  select   sum(差值)   as   '累计'  
  from  
          (  
                select   A.id  
                              ,isnull(abs(B.col-A.col),0)   as   '差值'  
                from   @tb   A  
                left   join   @tb   B   on   A.id=(select   min(id)    
                                                                        from   @tb    
                                                                              where   id>B.id)  
          )t  
  where   差值>10  
   
  --结果  
  /*  
  累计  
  -----------  
  11  
   
  (1   row(s)   affected)  
  */

 

declare   @t   table(col1   int)  
  insert   into   @t   select   1  
  union   all   select   3  
  union   all   select   14  
  union   all   select   15  
   
  select   identity(int,1,1)   id,*   into   #t   from   @t  
  select   sum(b.col1-a.col1)   '累计差额'   from   #t   a,#t   b    
  where   a.id=b.id-1   and   b.col1-a.col1>10  
  drop   table   #t 

 

declare   @tb   table  
  (  
        col   int  
  )  
  insert   @tb  
  select   1   union  
  select   3   union  
  select   14   union  
  select   15  
   
  select   id=identity(int,1,1),col=col   into   #t   from   @tb  
   
  select   sum(abs(a.col-b.col))  
  from   #t   a   left   join   (select   id=id-1,col   from   #t   where   id>1)   b  
  on   a.id=b.id    
  where   abs(a.col-b.col)>10  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值