简体   繁体   English

在SQL Server中获取两个相邻记录之间的值差

[英]Getting difference of value between two adjacent records in SQL Server

(Editing my post with data and expected result as per replies.) (根据回复,使用数据和预期结果编辑我的帖子。)

I have a table which looks as follows. 我有一张桌子,看起来如下。 I would like to compute the difference in Score between two adjacent records. 我想计算两个相邻记录之间的Score差异。

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

This is what I have tried. 这就是我尝试过的。

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'

But I always get the difference to be -1. 但是我总是得到的差是-1。

Expected result 预期结果

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

You can use lead to get the value from the next row and use it for subtraction. 您可以使用lead从下一行获取值并将其用于减法。 Note that this function is available in sql server 2012 and later versions. 请注意,此功能在sql server 2012和更高版本中可用。

If you need null to be the result when there is no leading row, remove the isnull condition. 如果在没有前导行时需要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'

You can implement ROW_NUMBER() in place of lead/lag if you are using pre-2012 SQL Server: 如果您使用的是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

You can try this: 您可以尝试以下方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM