我有一个像这样的 SQL 2008 数据库表
name score
-----------------------
steve 207
steve 205
steve 200
steve 139
我想得到行之间的差异。 eqn = [行 - (行 + 1)] 所以我理想情况下希望它是,
steve 2 //207 - 205
steve 5 //205 - 200
steve 61 //200 - 139
steve 139 //139 - 0
最好的方法是什么? 谢谢!
最佳答案
这是一种方法
with cte as
(SELECT
ROW_NUMBER() OVER (PARTITION BY table.name ORDER BY id) row,
name,
score
FROM table)
SELECT
a.name ,
a.score - ISNULL(b.score,0)
FROM
cte a
LEFT JOIN cte b
on a.name = b.name
and a.row = b.row+1
关于行之间的 SQL 差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6299950/