2016-08-18 66 views
0

我在面试中被问及此问题,无法破解它。 我有下列值在Oracle中将所有行转换为列

Id Name Sal 
1 Sid 1000 
2 Jon 800 
3 Ram 600 

我想如下要被显示的输出的Employee表:

1  2  3 
Sid Jon  Ram 
1000 800  600 

即行列。

我用case/decode为相同。但他需要不同的答案,因为可能会有更多的列,他不想为所有人使用解码。 我在网上搜索了枢轴和一些其他功能,但无法进行查询,可以提供给我这个输出。是否有可能以上述格式输出?如果是,我可以得到这个查询。我正在使用oracle。

在此先感谢。

回答

0

你可以使用listagg()

select listagg(id, ' ') within group (order by id) as list from employee union all 
select listagg(name, ' ') within group (order by id) from employee union all 
select listagg(sal, ' ') within group (order by id) from employee 

或类似这样的PL/SQL块:

declare 
    type lines is varray(3) of varchar2(32767); 
    ls lines := lines('', '', ''); 
begin 
    for r in (select id, name, sal from employee) loop 
    ls(1) := ls(1)||r.id||' '; 
    ls(2) := ls(2)||r.name||' '; 
    ls(3) := ls(3)||r.sal||' '; 
    end loop; 
    for i in 1..3 loop dbms_output.put_line(ls(i)); end loop; 
end; 
+0

感谢您的答复,但我不应该使用PL/SQL。此外,如果表中有30列,那么根据给定的查询,我将需要使用29'联合所有',这是不可行的。有没有其他方法? – kash

+0

嗯......没有'解码',没有联盟,没有PL/SQL ;-)我不知道其他方式,也许其他用户。 –