我怎樣才能在MS SQL表ID列表以數字顯示,我有「ORDER BY ID DESC」當前行的ID和前行的ID - 假設之間的差異如何獲得顯示當前行ID和先前行ID之間的減法結果的列表?
SELECT ID, ???? AS [CurrentID - PreviousID]
FROM foo
ORDER BY foo.ID DESC
我怎樣才能在MS SQL表ID列表以數字顯示,我有「ORDER BY ID DESC」當前行的ID和前行的ID - 假設之間的差異如何獲得顯示當前行ID和先前行ID之間的減法結果的列表?
SELECT ID, ???? AS [CurrentID - PreviousID]
FROM foo
ORDER BY foo.ID DESC
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
嘗試以下查詢中使用CTE
和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) |
爲什麼左連接?爲什麼不是「哪裏> 1」呢? – 2013-04-26 09:58:36
@DanBracuk,左連接用於選擇所有行。按照你的建議使用'Where'> 1',min id必須是1,這是硬編碼。他可以根據需要修改查詢。 – Kaf 2013-04-26 10:02:55
你能舉個例子嗎? – WiiMaxx 2013-04-26 10:03:33