繁体   English   中英

将所有行转置为Oracle中的列

[英]Transpose all rows into columns in Oracle

面试中有人问我这个问题,无法解决。 我有一个雇员表,具有以下值

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

我希望输出显示如下:

 1      2       3
Sid    Jon     Ram
1000   800     600

即行到列。

我用大小写/解码相同。 但是他需要不同的答案,因为可能会有更多的列,而且他不想对所有对象都使用解码。 我在网上搜索了Pivot和其他一些功能,但无法进行查询,无法向我提供此输出。 是否可以上述格式输出? 如果是,我可以查询这个。 我正在使用oracle。

提前致谢。

您可以使用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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM