在SQL Server

时间:2015-09-29 13:54:08

标签: sql sql-server

(根据回复编辑包含数据和预期结果的帖子。)

我有一张表格,如下所示。我想计算两个相邻记录之间Score的差异。

ID          TimeStamp               Score
1002010     9/26/2015 11:24:08 PM   32
1002010     9/28/2015 10:12:57 PM   38

这就是我的尝试。

SELECT
   [current].ID,
   [current].Score,
   ISNULL(convert(int,[next].Score), 0) - convert(int,[current].Score)
FROM
   RiskPredLog AS [current]
LEFT JOIN
   RiskPredLog AS [next] ON [next].ID = (SELECT MIN(ID) 
                                         FROM TableName 
                                         WHERE ID > [current].ID)
WHERE
   [current].ID = '1002010'

但我总是差别为-1。

预期结果

 ID         TimeStamp               Score
 -----------------------------------------------
 1002010    9/26/2015 11:24:08 PM   NULL
 1002010    9/28/2015 10:12:57 PM   6

3 个答案:

答案 0 :(得分:1)

您可以使用lead从下一行获取值并将其用于减法。请注意,此功能在sql server 2012及更高版本中可用。

如果在没有前导行时需要null作为结果,请删除isnull条件。

SELECT
ID,
Score,
ISNULL(convert(int, lead(Score) over(partition by id order by timestamp)), 0) 
- convert(int, Score)
FROM RiskPredLog 
-- where ID = '1002010'

答案 1 :(得分:0)

如果您使用的是2012之前的SQL Server,则可以实施ROW_NUMBER()代替lead/lag

SELECT
   [current].ID,
   [current].Score,
   ISNULL(convert(int,[next].Score), 0) - convert(int,[current].Score)
FROM
   (Select *,ROW_NUMBER() OVER (ORDER BY ID,TimeStamp) as rn from RiskPredLog) AS [current]
LEFT JOIN
   (Select *,ROW_NUMBER() OVER (ORDER BY ID,TimeStamp) as rn from RiskPredLog) AS [next]
      ON [next].rn = [current].rn + 1

答案 2 :(得分:0)

你可以试试这个:

SELECT  r.ID,
        r.Score,
        r.Score - ISNULL(LEAD(r.Score) OVER (ORDER BY r.TimeStamp DESC),0) AS ComputedScore
FROM    RiskPredLog r