如何比较两行数据并将差异放在其他列中?

时间:2016-08-23 10:02:51

标签: sql sql-server sql-server-2008-r2

       Diff  abc  
row1    3    xyz
row2    5    xyz
row3    10   xyz
row3    13   xyz
row3    15   xyz

我希望将两行的列(例如row2.Diff - row1.Diff)与任何其他列进行比较。

Result
2    (r2.diff  - r1.diff)
5    (r3.diff  - r2.diff)
3    (r4.diff  - r3.diff)
2   (r5.diff  - r4.diff)

2 个答案:

答案 0 :(得分:2)

特定于sql server的答案

;with cte
as
(
select *,row_number() over (order by diff) as rownum
from #tmp
)
select 
c1.*,c2.diff-c1.diff as result
from cte c1
left join
cte c2 on c1.rownum+1=c2.rownum

如果使用SQLserver2012或更高版本..

select *,isnull(lead(diff) over (order by diff)-diff,0) as difff
from #tmp

答案 1 :(得分:2)

在SQL Server 2008中,我会cross apply。行的顺序不是100%明确,但似乎基于diff

select t.diff - t2.diff
from t cross apply
     (select top 1 t2.*
      from t t2
      where t2.diff < t.diff
      order by t2.diff desc
     ) t2;