转置SQL表

时间:2017-12-05 15:51:09

标签: sql oracle pivot

我有以下表格(下表是简化更复杂的任务):

abc.FirstTable

ID | Name
---------
10 | test

abc.SecondTable

Id | RefId
----------
20 | 10
21 | 10

我想要的是:

Id | Name | RefId1 | RefId2
---------------------------
10 | test | 20     | 21

我坚持:

select t1.id, t1.name, t2.ID from abc.FirstTable t1
left join abc.SecondTable t2 on t2.refid = t1.id;

产生两行。有关如何使用连接扩展此查询的任何提示?谢谢!

1 个答案:

答案 0 :(得分:1)

with t as
( 
  select t1.id id1, t1.name, t2.* from abc_FirstTable t1 join abc_SecondTable t2 on t2.refid = t1.id
)
select * from t
pivot
(
 min(id) min_id, max(id) max_id 
 for (refid) in (10)
);