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

Popular posts from this blog

System.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out

Pre login Handshake or Connection Timeout Period

Transparent Data Encryption(TDE) with Master Key and Certificate in SQL Server