我有一个Audit类的表,我们根据其他表中的某些触发器存储一些信息。
ID,Changed_Column,OldValue,NewValue将可用。现在有可能使用相同的ID,因为更改后的列将具有不同的值,所以我希望将其重复3-4次,我想将它们合并到单行中并获取数据。例如,
ID ChangedColumn OldValue NewValue 1 Name Bob Roy 1 Age 26 28 1 Section B C
现在,当我们选择它时,它将把所有行显示为separte,但是我想自行加入并通过基于ID值的合并来仅检索一条记录
预期的结果是这样的,
ID Name Age Section ChangedColumns 1 was :Bob now : Roy was:26 now:28 Was:B now:C Name, Age, Section
可以对列名称进行分组以使用listagg功能。将行转换为列使用Pivot功能。
listagg
Pivot
with tab as( select 1 as id, 'Name' as col, 'Bob' as OldValue , 'Roy' as NewValue from dual union all select 1 as id, 'Age', '26', '28' as NewValue from dual union all select 1 as id, 'Section', 'B', 'C' as NewValue from dual ) select * from ( select id ,t.col as col ,max('was: '|| t.OldValue || ' now: ' || t.NewValue) as val ,listagg(t.col,',') within group(order by t.id) OVER (PARTITION BY null) as ChangedColumn from tab t group by id,t.col ) pivot ( max(val) for col in('Name','Age','Section'));