鉴于Table1和Table2如下,如何返回如下所示的结果集?
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
答案 0 :(得分:0)
您可以使用聚合来执行此操作:
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
答案 1 :(得分:0)
使用2个不同的别名将表1连接到表2两次。然后根据需要限制别名以从一个
获取role_1和从另一个获取role_2select
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";