Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to MERGE data into the target table based on certain conditions . Need to group by sequence and

Albert ChaoMar 14 2022
CREATE TABLE transact (
    seq_id     NUMBER(10),
    q_id       NUMBER(10),
    a_val      VARCHAR2(20),
    ref_pa_id  NUMBER(10),
    seq        NUMBER(10)
);

INSERT INTO transact VALUES(11,13,null,992,1);
INSERT INTO transact VALUES(11,13,null,637,2);
INSERT INTO transact VALUES(11,14,'Manual',null,3);
INSERT INTO transact VALUES(11,15,null,083,1);

Above is the table transact with data for which I need to load the same data into the another table transact_entry but with some conditions as mentioned below:
Target table :

CREATE TABLE transact_entry (
    seq_id   NUMBER(10),
    ref_id   NUMBER(10),
    sys_otr  VARCHAR2(20),
    int_otr  VARCHAR2(20)
);

Conditions:
I need to group the data as per the sequence. In the above data, we have total of 4 entries out of which we need to check seq column and find the unique. So, unique will come as 3 i.e sequence 1,2,3
q_id are static. So, we need to insert the record into the transact_entry table based on these q_id i.e 13,14,15
Lets start with seq 1 which has two q_id i.e 13 and 15. Then we need to load these records into transact_entry table. For 13, we will insert the ref_pa_id of transact table into the target table column ref_id and for 15, we will insert the a_val of transact table into the target table transact_entry column int_otr
Lets now check for seq 2. If q_id is 13 then we will insert the ref_pa_id of transact table into the target table transact_entry column ref_id
Lets now check for seq 3. If q_id is 14 then we will insert the a_val of transact table into the target table transact_entry column sys_otr
Expected output:

+--------+--------+---------+---------+
| seq_id | ref_id | sys_otr | int_otr |
+--------+--------+---------+---------+
|     11 |    992 |         | null    |
|     11 |    637 |         |         |
|     11 |        | Manual  |         |
+--------+--------+---------+---------+

Tool Used: SQL Developer(18c)
It has also been asked on Stackflow

This post has been answered by Frank Kulash on Mar 14 2022
Jump to Answer
Comments
Post Details
Added on Mar 14 2022
4 comments
1,274 views