How to return a redundant row for duplicate ID in single row in Oracle

房东的猫 提交于 2019-12-23 05:52:06

问题


I have a Audit kind of table where we store some information based on some triggers in other tables.

ID, Changed_Column, OldValue, NewValue will be available. Now there is a possibility for same Id there will be 3-4 duplicates since the changed column will have different values I wants to merge them into single row and take data For exmaple,

ID   ChangedColumn OldValue NewValue
1    Name           Bob     Roy
1    Age            26      28  
1    Section        B       C

When we select now it will display all the rows into separte but I wants to self join and retrieve only one record by merging based on ID value

Expected result is like,

ID   Name               Age           Section     ChangedColumns
1    was :Bob now : Roy was:26 now:28 Was:B now:C Name, Age, Section

回答1:


to Group the column names you can use listagg function. to convert rows to columns use Pivot function.

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 here




回答2:


This seems pretty simple to do using conditional aggregation:

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;

Here is a db<>fiddle.



来源:https://stackoverflow.com/questions/56439988/how-to-return-a-redundant-row-for-duplicate-id-in-single-row-in-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!