I have an customer_audit table, that logs INSERT and UPDATE happened on a customer table.
customer_audit
id | operation | timestamp | customer_id | address1 | address2 |
---|---|---|---|---|---|
1 | I | 2024-10-05 | 100 | link st | number 1 |
2 | U | 2024-10-06 | 100 | link st | number 2 |
3 | U | 2024-10-07 | 100 | link road | number 2 |
4 | U | 2024-10-08 | 100 | link road | number 200 |
5 | I | 2024-10-06 | 200 | park st | number 20 |
6 | U | 2024-10-08 | 200 | park st | number 200 |
The expected output, in this case for address1
and address2
, displays all historical values for address1 and address2 separately, with from_date
and to_date
calculated from the timestamp column.
E.g. for customer_id 100:
customer_id | column_name | column_value | from_date | to_date |
---|---|---|---|---|
100 | address1 | link st | 2024-10-05 | 2024-10-07 |
100 | address1 | link road | 2024-10-07 | null (meaning column value is current) |
100 | address2 | number 1 | 2024-10-05 | 2024-10-06 |
100 | address2 | number 2 | 2024-10-06 | 2024-10-08 |
100 | address2 | number 200 | 2024-10-08 | null |
I managed to solve it by tweaking what mcwolf’s query a bit:
select customer_id, name, 'address1' as attribute_name, address1 as "attribute_value", min(from_date) as "valid_from", max(to_date) as "valid_to"
from (
select customer_id,
name,
address1,
"mod_timestamp" from_date,
COALESCE(lead("mod_timestamp") over change_window, to_date('99991231', 'yyyymmdd')) to_date,
ROW_NUMBER () OVER ( PARTITION BY customer_id, address1 ORDER BY mod_timestamp) as rownum
from customer_audit
WINDOW change_window as (PARTITION BY customer_id order by mod_timestamp)
order by customer_id, mod_timestamp ) a
group by customer_id, name, attribute_name, "attribute_value"
order by customer_id, "valid_from";
2
Answers
… here is another way to do it …
See the fiddle here.
Your appended answer does not seem to work for me. This does:
fiddle
Repeat the same for
address2
and append results. Both operations are mostly independent as they form different groups.Related (with links to more):