如何获得一个列字段的两行之间的差异?

我有这样一张桌子:

rowInt Value 2 23 3 45 17 10 9 0 .... 

列rowInt值是整数,但不是以相同的增量排列。 我可以使用下面的SQL按rowInt列出值:

 SELECT * FROM myTable ORDER BY rowInt; 

这将按rowInt列出值。 如何得到两行之间Value的差异,结果如下:

 rowInt Value Diff 2 23 22 --45-23 3 45 -35 --10-45 9 0 -45 --0-45 17 10 10 -- 10-0 .... 

该表在SQL 2005(Miscrosoft)

 SELECT [current].rowInt, [current].Value, ISNULL([next].Value, 0) - [current].Value FROM sourceTable AS [current] LEFT JOIN sourceTable AS [next] ON [next].rowInt = (SELECT MIN(rowInt) FROM sourceTable WHERE rowInt > [current].rowInt) 

编辑:想一想,在select使用子查询(ala Quassnoi的答案)可能会更有效率。 我会试用不同的版本,并看看执行计划,看看哪些将在数据集的大小,你有最好的performance…

 SELECT rowInt, Value, COALESCE( ( SELECT TOP 1 Value FROM myTable mi WHERE mi.rowInt > m.rowInt ORDER BY rowInt ), 0) - Value AS diff FROM myTable m ORDER BY rowInt 

如果您确实想要确认订单,请使用“Row_Number()”并比较当前logging的下一个logging(仔细看“on”子句)

 T1.ID + 1 = T2.ID 

你基本上是join当前行的下一行,没有指定“min”或者做“top”。 如果您的logging数量较less,“Dems”或“Quassanoi”的其他解决scheme将正常工作。

 with T2 as ( select ID = ROW_NUMBER() over (order by rowInt), rowInt, Value from myTable ) select T1.RowInt, T1.Value, Diff = IsNull(T2.Value, 0) - T1.Value from ( SELECT ID = ROW_NUMBER() over (order by rowInt), * FROM myTable ) T1 left join T2 on T1.ID + 1 = T2.ID ORDER BY T1.ID 

SQL Server是否支持分析function?

 select rowint, value, value - lag(value) over (order by rowint) diff from myTable order by rowint / 

SQL Server 2012并支持LAG / LEAD函数来访问上一行或后一行。 SQL Server 2005不支持这一点(在SQL2005中,你需要一个连接或其他东西)。

此数据的SQL 2012示例

 /* Prepare */ select * into #tmp from ( select 2 as rowint, 23 as Value union select 3, 45 union select 17, 10 union select 9, 0 ) x /* The SQL 2012 query */ select rowInt, Value, LEAD(value) over (order by rowInt) - Value from #tmp 

LEAD(值)将返回与“over”子句中给定的顺序有关的下一行的值。

 select t1.rowInt,t1.Value,t2.Value-t1.Value as diff from (select * from myTable) as t1, (select * from myTable where rowInt!=1 union all select top 1 rowInt=COUNT(*)+1,Value=0 from myTable) as t2 where t1.rowInt=t2.rowInt-1 

查询查找单列的2行之间的date差异

 SELECT Column name, DATEDIFF( (SELECT MAX(date) FROM table name WHERE Column name < b. Column name), Column name) AS days_since_last FROM table name AS b