1

我有一个记录为的表:

ID  |NAME   |FULLNAME
ID1 |John   |John S
ID1 |Tom    |Tom S
ID2 |Tin    |Tin J
ID2 |Jim    |Jim B
ID2 |Kethy  |Kethy T
ID3 |Neo    |Neo L

我想创建一个新表并插入如下记录:

ID  |NAME1  |FULLNAME1  |NAME2  |FULLNAME2  |NAME3         |FULLNAME3
ID1 |John   |John S     |Tom    |Tom S      
ID2 |Tin    |Tin J      |Jim    |Jim B      |Kethy         |Kethy T
ID3 |Neo    |Neo L  

新表的结构是固定的,总共有 7 列。

4

2 回答 2

1

试试下面的语句:

CREATE TABLE new_table AS
SELECT name1.id
     , name1.name AS name1
     , name1.fullname AS fullname1
     , name2.name AS name2
     , name2.fullname AS fullname2
     , name3.name AS name3
     , name3.fullname AS fullname3
  FROM ( SELECT * 
           FROM ( SELECT id, name, fullname
                       , rank() over ( partition by id order by fullname asc) as rank 
                    FROM old_table )
          WHERE rank = 1) name1
     , ( SELECT * 
           FROM ( SELECT id, name, fullname
                       , rank() over ( partition by id order by fullname asc) as rank 
                    FROM old_table )
          WHERE rank = 2) name2
     , ( SELECT * 
           FROM ( SELECT id, name, fullname
                       , rank() over ( partition by id order by fullname asc) as rank 
                    FROM old_table ) 
          WHERE rank = 3) name3
 WHERE name1.id = name2.id (+)
   AND name1.id = name3.id (+)
 ORDER BY name1.id ASC;

可能有一些方法可以以某种方式对其进行优化,但它似乎会产生您正在寻找的结果。

于 2013-06-13T06:58:58.877 回答
0

如果您的数据库版本是 11g 或更高版本,您可以使用 pivot 函数,它可以将行转换为列。这里的例子:http ://www.dba-oracle.com/t_pivot_examples.htm

确定您的数据库版本:如何确认数据库是 Oracle 以及它使用 SQL 的版本?

select * from v$version;
于 2013-06-18T05:17:54.340 回答