首页 > 解决方案 > 行到列数据

问题描述

我有表名为AA. 我有 3 列,即x,y,z 。它只有一排。

select * from aa;

x   y  z
10 20 30

我想要像这样的输出

10
20
30

我使用了以下查询

select x from AA union all select y from AA union all select z from AA ;

它正在提供所需的输出。但有人告诉我这是不可行的查询。你们中的任何人都可以为我提供最佳解决方案。

标签: sqloracleunpivot

解决方案


您的查询很好:

select x from AA union all
select y from AA union all
select z from AA ;

更高效的版本更长一点:

select (case when n = 1 then x
             when n = 2 then y
             else z
        end) as x
from (select 1 as n from dual union all select 2 union all select 3
     ) cross join
     AA;

最新版本的 Oracle 支持横向连接和apply. 如果您正在使用一个,我建议:

select d(x)
from aa cross apply
     (select aa.x from dual union all
      select aa.y from dual union all
      select aa.z from dual
     ) d

推荐阅读