Skip to content
Advertisement

SQL Return last record where column value changed and amount of change

In MS SQL 2012, I have a table like such:

I would like to return the date of change and the amount of change — from the last record where the value changed from the record before it.

Ideally, this:

Entity A last changed on 1/1/2018 by 100, Entity B last changed on 1/1/2019 by 150

I’m thinking it’s going to be some combination of Lag and maybe this discussion: SQL: selecting rows where column value changed from previous row

But I’m very much a SQL beginner and have no formal training, and I appreciate any detail and extra explanations you can provide.

Thank you!

Advertisement

Answer

First with a CTE which returns all the changes and then with NOT EXISTS that returns the last change for each Entity:
(Edited with the actual table and column names)

See the demo.
Results:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement