Thursday, November 23, 2017

Difference between same column Value in Current & Previous Row

DECLARE @Tbl TABLE(RowID INT,RawValue int)

INSERT INTO @Tbl(RowID,RawValue)
values('1','12'),('2','25'),('3','10'),('4','50'),('5','35')

SELECT * FROM @Tbl
SELECT *,SUM(RawValue) OVER (PARTITION BY 1) FROM @Tbl

SELECT
   [current].RowID,
   [current].RawValue,
   ISNULL([next].RawValue, 0) - [current].RawValue
FROM
   @Tbl       AS [current]
LEFT JOIN
   @Tbl       AS [next]
      ON [next].RowID = (SELECT MIN(RowID) FROM @Tbl WHERE RowID > [current].RowID)

No comments:

Post a Comment