I have two tables Table 1 (main) and Table 2,connected with T1.
I need to delete double entries in Table 1. TO do that before any delete in T1 I must delete or update the data in T2.
The option chosen is to update T2 data to point with entries not to be deleted in T1.
SQL Problem :
I have the following group by expresion :
SELECT min(t1.id) minid ,max(t1.id) maxid ,t1.t1_value t1valor ,t1.group_id grupo ,t1.date_begin ,t1.date_end ,count(*) FROM rs2qtt1 t1 WHERE t1.t1_value LIKE '%B0%' GROUP BY t1.t1_value ,t1.group_id ,t1.date_begin ,t1.date_end HAVING count(*) > 1 ORDER BY count(*) DESC ,t1.t1_value ,t1.group_id ,t1.date_begin
I want to do something like that avoiding PL/SQL if it’s possible.
UPDATE rs2qtt2 t2 SET t2.rg_id = minid WHERE t2.rg_id IN ( SELECT maxid max2 FROM ( SELECT min(t1.id) minid ,max(t1.id) maxid ,t1.t1_value t1valor ,t1.group_id grupo ,t1.date_begin ,t1.date_end ,count(*) FROM rs2qtt1 t1 WHERE t1.t1_value LIKE '%B0%' GROUP BY t1.t1_value ,t1.group_id ,t1.date_begin ,t1.date_end HAVING count(*) > 1 ORDER BY count(*) DESC ,t1.t1_value ,t1.group_id ,t1.date_begin ) );
But obviously the minid
in the set statement is not visible.
Advertisement
Answer
You can prepare the required values in a query with saved rowid
from rs2qtt2
and then use it as source data for merge
query like
merge into rs2qtt2 dst using ( select t2.rowid row_id, t1.minid new_id from ( SELECT min(t1.id) minid, max(t1.id) maxid FROM rs2qtt1 t1 WHERE t1.t1_value LIKE '%B0%' GROUP BY t1.t1_value, t1.group_id, t1.date_begin, t1.date_end HAVING count(*) > 1 ) t1 inner join rs2qtt2 t2 on (t2.rg_id = t1.maxid) ) src on (dst.rowid = src.row_id) when matched then update set dst.rg_id = src.new_id;
This should help to avoid ORA-38104
and should access rows for merging directly by rowid