Given Table1 and Table2 as below how to return the resultset shown below?
TABLE1
TBL1_PK TBL1_COL2
1 A
TABLE2
TBL2_PK TABLE1_FK ROLE_CD FIRST_NAME LAST_NAME
1 1 ROLE_1 DEF GHI
2 1 ROLE_2 JKL MNP
3 1 ROLE_3 RST UVW
RESULSET
TBL1_COL2 ROLE_1_FIRST_NAME ROLE1_LAST_NAME ROLE_2_FIRST_NAME ROLE_2_LAST_NAME
A DEF GHI JKL MNP
You can use aggregation to do this:
select t1.TBL1_COL2,
max(case
when t2.role_cd = 'ROLE_1'
then t2.first_name
end) ROLE_1_FIRST_NAME,
max(case
when t2.role_cd = 'ROLE_1'
then t2.last_name
end) ROLE1_LAST_NAME,
max(case
when t2.role_cd = 'ROLE_2'
then t2.first_name
end) ROLE_2_FIRST_NAME,
max(case
when t2.role_cd = 'ROLE_2'
then t2.last_name
end) ROLE2_LAST_NAME
from table1 t1
join table2 t2 on t1.tbl1_pk = t2.table1_fk
group by t1.TBL1_COL2
Join table 1 to table 2 twice with 2 different aliases. Then restrict the aliases as needed to get role_1 from one and role_2 from the other
select
T1.TBL1_COL2 as "TBL1_COL2",
T2R1.FIRST_NAME as "Role_1_first_name",
T2R1.Last_name as "Role_1_last_name",
T2R2.First_name as "Role_2_first_name",
T2R2.Last_name as "Role_2_last_name"
from
Table1 as T1
inner join Table2 as T2R1 on T1.TBL1_PK = T2R1.Table1_fk
inner join Table2 as T2R2 on T2.TBL1_PK = T2T2.Table1_fk
where
T2R1.role_cd = "Role_1"
and T2T2.role_cd = "Role_2";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.