行之间的SQL差异

时间:2011-06-09 22:12:57

标签: sql database

我有一个像这样的SQL 2008数据库表

name      score
-----------------------
steve     207
steve     205
steve     200
steve     139

我希望得到行之间的差异。 eqn = [row - (row + 1)] 所以我理想的是希望它成为,

steve 2   //207 - 205
steve 5   //205 - 200
steve 61  //200 - 139
steve 139 //139 - 0

最好的方法是什么? 谢谢!

2 个答案:

答案 0 :(得分:17)

这是一种方法

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

答案 1 :(得分:6)

另一种方法是使用lag():

SELECT
   name,
   score - coalesce(lag(score) over (partition by name order by id), 0)
FROM table
ORDER BY name, id

TSQL中的lag()函数doesn't seem to be available,但在注释中建议使用此解决方法:

select name,
    score - coalesce(
    MIN(score) OVER (PARTITION BY name ORDER BY id
             ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING)
    , 0) as diff
from table
order by name, id