Jam*_*s L 6 sql oracle select plsql oracle9i
我们有一个表格形式:
ID,Value1,Value2,Value3
1,2,3,4
Run Code Online (Sandbox Code Playgroud)
我们需要将其转化为.
ID,Name,Value
1,'Value1',2
1,'Value2',3
1,'Value3',4
Run Code Online (Sandbox Code Playgroud)
在一个SELECT语句中是否有一种聪明的方法(即没有UNION)?列名称Value1,Value2和Value3是固定且常量的.
该数据库是oracle 9i.
试一试union
.
select ID, 'Value1' as Name, Value1 as Value from table_name union all
select ID, 'Value2', Value2 as Value from table_name union all
select ID, 'Value3', Value3 as Value from table_name
order by ID, Name
Run Code Online (Sandbox Code Playgroud)
使用union all
意味着服务器不会执行distinct
(union
操作中隐含).它不应该对数据产生任何影响(因为你的ID应该是HOPEFULLY不同),但它可能会加快一点.
这适用于 Oracle 10g:
select id, 'Value' || n as name,
case n when 1 then value1 when 2 then value2 when 3 then value3 end as value
from (select rownum n
from (select 1 from dual connect by level <= 3)) ofs, t
Run Code Online (Sandbox Code Playgroud)
我认为 Oracle 9i 有递归查询?不管怎样,我很确定它有 CASE 支持,所以即使它没有递归查询,你也可以只做“(select 1 from Dual Union all select 2 from Dual Union all select 3 from Dual) ofs”。对于 Oracle 来说,滥用递归查询更为普遍。(不过,使用联合生成行可以移植到其他数据库)