例表D1
 
 nyr           P8             P14          P201/1/05         35              32          40
1/2/05         53              21          18
1/3/05         64              12          60
1/4/05         37              31          13
1/5/05         25              52          25
1/6/05         11              30          59
1/7/05         56              42          37
1/8/05         28              16          69
1/9/05         38              45          15
 .
 .
 .我用下面的SQL:select a.P14-b.P14 from D1 a,D1 b where datediff(day,b.nyr,a.nyr)=1  得到如下结果(D2表):p14    -11    
-9    
 19    
 21     
-22    
 12     
-26     
 29     
 .       
 .
 .
问题(1):要怎么写SQL才能在D1表中直接实现D2表的后一项减去前一项,得到如下结果(D3表):p14      2     
 28    
 2     
-43    
 34    
-38     
 55    
 .
 .
 .
问题(2):要怎么写SQL才能在D1表中直接实现D3表的后一项减去前一项,得到如下结果:p14      26     
-26     
-45            
 77           
-72           
 93           
 .
 .
 .

解决方案 »

  1.   

    declare @a table(nyr smalldatetime, P8 int, P14 int, P20 int)
    insert @a select '1/1/2005', 35, 32, 40
    union all select '1/2/2005', 53, 21, 18
    union all select '1/3/2005', 64, 12, 60
    union all select '1/4/2005', 37, 31 ,13
    union all select '1/5/2005', 25 ,52, 25
    union all select '1/6/2005', 11, 30, 59
    union all select '1/7/2005', 56, 42, 37
    union all select '1/8/2005', 28, 16, 69
    union all select '1/9/2005', 38, 45, 15select (a.p14+b.p14)-(select 2*p14 from @a  where nyr=dateadd(day,-1,a.nyr)) from @a a,@a b where datediff(day,b.nyr,a.nyr)=2
      

  2.   

    不好意思,我的意思是说怎么通过NYR字段的关联,直接从D1表得到问题1和问题2的结果.麻烦大家了.