2013-04-26 43 views

回答

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) | 
+0

爲什麼左連接?爲什麼不是「哪裏> 1」呢? – 2013-04-26 09:58:36

+0

@DanBracuk,左連接用於選擇所有行。按照你的建議使用'Where'> 1',min id必須是1,這是硬編碼。他可以根據需要修改查詢。 – Kaf 2013-04-26 10:02:55

相關問題