如何获得显示当前行ID和上一行ID的减法结果的列表?

时间:2013-04-26 09:43:30

标签: sql sql-server-2008 tsql

如何在MS SQL表中获取ID列表,其中一个数字显示当前行ID与前一行ID之间的差异 - 假设我有'ORDER BY ID DESC'

SELECT ID, ???? AS [CurrentID - PreviousID]
FROM foo
ORDER BY foo.ID DESC

2 个答案:

答案 0 :(得分:1)

使用CTErow_number()

尝试以下查询

Fiddle Demo

create table foo (id int)

insert into foo values 
(1),(5),(8),(9)

;with cte as (
   select Id, row_number() over (order by id desc) rn
   from foo
)
select c1.id, c1.id-c2.id as [currentId - previousId]
from cte c1 
      left join cte c2 on c1.rn = c2.rn - 1
order by c1.rn

| ID | CURRENTID - PREVIOUSID |
-------------------------------
|  9 |                      1 |
|  8 |                      3 |
|  5 |                      4 |
|  1 |                 (null) |

答案 1 :(得分:0)

SELECT
  ID,
  ID - coalesce(
                 (select max(ID) from foo foo2 where foo2.id<foo.id)
                , 0) as Diff
FROM foo
ORDER BY foo.ID DESC

http://sqlfiddle.com/#!3/1f21eb/3