How can I write a query to extract individual changes from snapshots of data?

后端 未结 2 1881
天命终不由人
天命终不由人 2020-12-20 02:39

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

2条回答
  •  爱一瞬间的悲伤
    2020-12-20 03:03

    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
    

提交回复
热议问题