I need to create a process that will extract the changes from a table where each row is a snapshot of a row in another table. The real-world problem involves many tables wit
WITH Snapshots (Sequence, DateTaken, ID, Field, FieldValue, _Index) AS
(
SELECT
Sequence,
DateTaken,
ID,
'Field1' AS Field
CAST(Field1 AS VARCHAR(100)) AS FieldValue, -- Find an appropriate length
ROW_NUMBER() OVER (ORDER BY ID, Sequence)
FROM
#Snapshots
UNION ALL
SELECT
Sequence,
DateTaken,
ID,
'Field2' AS Field
CAST(Field2 AS VARCHAR(100)) AS FieldValue, -- Find an appropriate length
ROW_NUMBER() OVER (ORDER BY ID, Sequence)
FROM
#Snapshots
)
SELECT
S1.DateTaken,
S1.ID,
S1.Field,
S1.FieldValue AS Previous,
S2.FieldValue As New -- Not necessarily "Current"
FROM
Snapshots S1
INNER JOIN Snapshots S2 ON
S2.ID = S1.ID AND
S2.Field = S1.Field AND
S2._Index = S1._Index + 1 AND
S2.FieldValue <> S1.FieldValue -- Might need to handle NULL values