客户要求将Oracle DB SQL中的1行拆分为6行。
比方说,最初,SQL(具有多个联接的复杂sql等)提取了9列:
从X,Y,Z中选择A,B,C,D,E,F,G,H,I。 。 。 (但查询非常复杂)
1)A,B,C,D,E,F,G,H,I。
现在,客户要求返回的每行都返回上述模式,新的输出应如下所示:
1)A,B,C,'D',D
2)A,B,C,'E',E
3)A,B,C,'F',F
4)A,B,C,'G',G
5)A,B,C,'H',H
6)A,B,C,“我”,我
基本上,第1 3列将在所有6个新行中重复。
对于原始查询中的每一行都重复该过程。
这可能吗?如果是,怎么办?
答案 0 :(得分:1)
使用union all
可能最简单:
select a, b, c, 'D' as which, d as val from t union all
select a, b, c, 'E', e from t union all
select a, b, c, 'F', f from t union all
select a, b, c, 'G', g from t union all
select a, b, c, 'H', j from t union all
select a, b, c, 'I', i from t ;
这是最简单的方式,但不是最有效的。它将为每列扫描一次表。从性能的角度来看,对于不太大的表,这可能很好(该表已缓存在内存中)。
如果“表格”确实是一个视图,那么性能可能是一个更重要的问题。
答案 1 :(得分:0)
您只需要unpivot
子句即可垂直显示数据:
with t(a,b,c,d,e,f,g,h,i) as
(
select 1,2,3,'D','E',2,3,'X','Y' from dual
)
select a,b,c,val from
(
select a,b,c,to_char(d) as d, to_char(e) as e, to_char(f) as f, to_char(g) as g,
to_char(h) as h, to_char(i) as i
from t
)
unpivot
( val for col in (d,e,f,g,h,i) )
order by col
to_char()转换的实现是为了避免 ORA-01790: 表达式必须具有与相应表达式相同的数据类型错误。