【发布时间】:2013-03-20 20:30:34
【问题描述】:
我有一个更复杂的下表:
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)
);
【问题讨论】:
-
什么版本的Oracle?每个
ID只会有 3 个条目吗? -
11g。有些会有两个,但最多 3 个
标签: oracle plsql oracle11g pivot unpivot