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 join multiple tables and printing the result for same id which are populating more than one i

Albert ChaoDec 8 2021
CREATE TABLE details_1 (
    e_id    NUMBER(10),
    e_name  VARCHAR2(30),
    CONSTRAINT pk_details_1_e_id PRIMARY KEY ( e_id )
);

insert into details_1 values(11,'A');


CREATE TABLE ques_ans (
    ques_ans_id  NUMBER(10),
    ref_ques_id  NUMBER(10),
    ref_ans_id   NUMBER(10),
    e_id         NUMBER(10),
    CONSTRAINT pk_ques_ans PRIMARY KEY ( ques_ans_id ),
    CONSTRAINT fk_ques_ans FOREIGN KEY ( e_id )
        REFERENCES details_1 ( e_id ),
        constraint fk_ques_and_ques_id foreign key(ref_ques_id)
        references ques_ref (ques_id)
);

insert into ques_ans values(1,3,1,11);
insert into ques_ans values(2,2,2,11);
insert into ques_ans values(3,4,1,11);

CREATE TABLE ques_ref (
    ques_id     NUMBER(10),
    code        VARCHAR2(50),
    code_label  VARCHAR2(100),
    constraint pk_ques_ref primary key(ques_id)
);

insert into ques_ref values(3,'changes_exist','Any known changes');
insert into ques_ref values(2,'E_Clubbed','E_id clubbed with other');
insert into ques_ref values(4,'E_impacted','E impacted by other');

CREATE TABLE ans_ref (
    ref_ans_id  NUMBER(10),
    code        VARCHAR2(10),
    code_value  VARCHAR2(30)
);

insert into ans_ref values(1,'R_Yes','Yes');
insert into ans_ref values(2,'R_No','No');

The problem facing in joining the tables :
Table ques_ans has ref_ques_id column that is being populated from ques_ref table. So, If ref_ques_id = 3 and ref_ans_id = 1 then it should display 'Yes' i.e populating from ans_ref table. Likewise for ref_ques_id = 2 then it should display 'No' and same for ref_ques_id = 4.
My Attempt :

select d.e_id, qa.ref_ques_id,
ar.code_value

from details_1 d
join ques_ans qa on(d.e_id = qa.e_id)
join ans_ref ar on(ar.ref_ans_id = qa.ref_ans_id) ;

In my attempt, I am getting 3 rows but ideally expected output should be like attached in the screenshot.
Expected Output
Columne e_id : Coming from details_1 table
Column Changes_exist: Validation in the ques_ans table ref_ques_id column and based on the ref_ans_id printing Yes or no.
Column E_clubbed: Validation in the ques_ans table ref_ques_id column and based on the ref_ans_id printing Yes or no.
Column E_Impacted: Validation in the ques_ans table ref_ques_id column and based on the ref_ans_id printing Yes or no.
The output should be like the attached screenshot but I got stuck that how this can be printed in a single row
Tool: SQL Developer Version: 20.4

This post has been answered by Solomon Yakobson on Dec 8 2021
Jump to Answer
Comments
Post Details
Added on Dec 8 2021
2 comments
2,594 views