gpt4 book ai didi

sql-server-2005 - 如何使用递归 CTE 获取前一行和当前行值?

转载 作者:行者123 更新时间:2023-12-03 23:37:53 24 4
gpt4 key购买 nike

考虑以下

Id  Nums
1 10
2 20
3 30
4 40
5 50

预期输出
Id  CurrentValue    PreviousValue
1 10 Null
2 20 10
3 30 20
4 40 30
5 50 40

我正在尝试以下但没有运气
;With Cte(Id,CurrValue,PrevValue) As
(
Select
Id
,CurrentValue = Nums
,PreviousValue = Null
From @t Where Id = 1
Union All
Select
t.Id
,c.CurrValue
,c.PrevValue
From Cte c
Join @t t On c.Id <= t.Id + 1

)
Select *
From Cte

需要帮助

最佳答案

这假设增加 ID 值并将处理 ID 中的差距

SELECT
ID,
This.Number AS CurrentValue,
Prev2.Number AS PreviousValue
FROM
myTable This
OUTER APPLY
(
SELECT TOP 1
Number
FROM
myTable Prev
WHERE
Prev.ID < This.ID -- change to number if you want
ORDER BY
Prev.ID DESC
) Prev2;

或者
WITH CTE
AS (SELECT ID,
Number,
ROW_NUMBER() OVER (ORDER BY ID) AS rn
FROM Mytable)
SELECT ID,
This.Number AS CurrentValue,
Prev.Number AS PreviousValue
FROM CTE This
LEFT JOIN CTE Prev
ON Prev.rn + 1 = This.rn;

对于 SQL Server 2012
SELECT
ID,
Number AS CurrentValue,
LAG(Number) OVER (ORDER BY ID) AS PreviousValue
FROM
MyTable

关于sql-server-2005 - 如何使用递归 CTE 获取前一行和当前行值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9127636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com