I have audit for records in a table. There multiple columns and each records states for a change of 1 or more columns.
I need to return an audit result where the return pattern will be: column (id, alias or name), previous value, new value, etc.
The problem is in that there can be multiple columns with changed data per each new record. At the same time the quantity of auditable columns is 5 so it’s possible to “hardcode” there names and changes verifications.
So is it possible to compose such a query in a shortened manner not just using UNIONS and make a SELECT query for each column and check for change?
Let’s say there is the table with the columns:
id, datetime value, int value, varchar value.
And if I have 2 records with such a data change as like:
id1, value1, value1, value1
id1, value2, value1, value2
Then I expect such audit results:
id1, value1 as oldvalue, value2 as newvalue, column2name as columnname
id1, value1 as oldvalue, value2 as newvalue, column4name as columnname
If I haven’t missed anything:
Basically, the idea is to rank contiguous groups of identical values and pick first occurrences of every value. That is done for every column whose values are being audited, and the columns are unpivoted in the process. Afterwards, the unpivoted row set is joined to itself, i.e. for every PK and column name, every row is matched to its predecessor (based on the ranking) to obtain the old value in the same row for the final result set.