我有一个审计类的表,我们根据其他表中的一些触发器存储一些信息。
ID,Changed_Column,OldValue,NewValue将可用。现在有可能使用相同的Id,会有3-4个重复,因为更改后的列将有不同的值,我希望将它们合并为单行,并为exmaple获取数据,
ID ChangedColumn OldValue NewValue
1 Name Bob Roy
1 Age 26 28
1 Section B C当我们选择现在,它将显示所有行为分隔,但我想要自我连接和检索只有一个记录通过合并基于ID值
预期的结果是,
ID Name Age Section ChangedColumns
1 was :Bob now : Roy was:26 now:28 Was:B now:C Name, Age, Section发布于 2019-06-04 09:15:59
要对列名进行分组,可以使用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'));db<>fiddle https://dbfiddle.uk/?rdbms=oracle_18&fiddle=de694207bf1221e95372b7953bffe1a3
发布于 2019-06-04 11:20:35
使用条件聚合似乎非常简单:
select id,
max(case when col = 'Name' then str end) as name,
max(case when col = 'Age' then str end) as age,
max(case when col = 'Section' then str end) as section
from (select t.*, ('was: ' || OldValue || ' now: ' || NewValue) as str
from t
) t
group by id;这里是db<>fiddle。
https://stackoverflow.com/questions/56439988
复制相似问题