LAG function in SQL Server( Getting difference between values from the same column)
The below query will get the difference between the values of the same column not difference between two different columns. Here is the query, the query will showing the difference between OrderQty.
USE DatabaseNameHere GO DECLARE @TEST TABLE (OrderID INT, OrderQty INT) INSERT INTO @TEST VALUES(1,5),(2,7),(3,10),(4,15),(5,17),(6,21),(7,30),(8,37), (9,40) SELECT * FROM @TEST SELECT OrderID,OrderQty,[Difference]=OrderQty-LAG(OrderQty)OVER(ORDER BY(OrderQty)) FROM @TEST
Comments