我有下表的更复杂版本:
ID | FIRST | LAST | EMAIL
1 | John | Doe | jdoe@example.com
1 | Mack | Johnson | mjohnson@example.com
1 | Steven | Michaels | smichaels@example.com
2 | Sarah | Sampson | ssampson@example.com
2 | Tom | Smith | tsmith@example.com
2 | Jane | Rogers | jrogers@example.com
3 | Bob | Johns | bjohns@example.com
3 | Kim | Lane | klane@example.com
3 | Ron | Swanson | rswanson@example.com
我想编写一个查询,将这些数据插入到另一个表中,看起来像这样(表已经存在):
ID | first1 | last1 | email1 | first2 | last2 | email2 | first3 | last3 | email3
1 | John | Doe | jdoe@example.com | Mack | Johnson | mjohnson@example.com | Steven | Michaels | smichaels@example.com
2 | Sarah | Sampson | ssampson@example.com | Tom | Smith | tsmith@example.com | Jane | Rogers | jrogers@example.com
3 | Bob | Johns | bjohns@example.com | Kim | Lane | klane@example.com | Ron | Swanson | rswanson@example.com
我觉得这应该很容易,但这个概念让我望而却步。实现这一目标的最佳实践是什么?
也许我还应该提到我写了一个函数,我可以传递 ID、索引号和列名来返回值(即 getpersoninfo(2,'1','first') 来返回 Sarah)。
select a_id,
FIRST1, LAST1, EMAIL1,
FIRST2, LAST2, EMAIL2,
FIRST3, LAST3, EMAIL3
from
(
select a_id, col||rn as new_col, value
from
(
select a_id, first_name, last_name, email,
cast(row_number() over(partition by a_id order by a_id) as varchar2(10)) rn
from dump_recs_2015
)
unpivot
(
value
for col in (first_name, last_name, email)
)
)
pivot
(
max(value)
for new_col in ('FIRST1' FIRST1, 'LAST1' LAST1, 'EMAIL1' EMAIL1,
'FIRST2' FIRST2, 'LAST2' LAST2, 'EMAIL2' EMAIL2,
'FIRST3' FIRST3, 'LAST3' LAST3, 'EMAIL3' EMAIL3)
);