0

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

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

2 回答 2

1

尝试使用CTEand进行以下查询row_number()

小提琴演示

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) |
于 2013-04-26T09:56:55.053 回答
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

于 2013-04-26T10:01:26.627 回答