列数乘以行数

时间:2019-01-15 14:47:07

标签: sql oracle pivot

我有一张这样的桌子:

  +------+--------+--------+--------+
  | TYPE | PROP_X | PROP_Y | PROP_Z |
  +------+--------+--------+--------+
  |    1 | x1     | y1     | z1     |
  |    2 | x2     | y2     | z2     |
  |    3 | x3     | y3     | z3     |
  |    4 | x4     | y4     | z4     |
  +------+--------+--------+--------+

如何获得这样的结果:

+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+
| PROP_X_1 | PROP_X_2 | PROP_X_3 | PROP_X_4 | PROP_Y_1 | PROP_Y_2 | PROP_Y_3 | PROP_Y_4 | PROP_Z_1 | PROP_Z_2 | PROP_Z_3 | PROP_Z_4 |
+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+
| x1       | x2       | x3       | x4       | y1       | y2       | y3       | y4       | z1       | z2       | z3       | z4       |
+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+----------+

我猜想,运算符PIVOT可以用于此目的,但我不知道该怎么做。

P.S。为表创建脚本:

create table my_table(type number(1), prop_x varchar2(30 char), prop_y varchar2(30 char), prop_z varchar2(30 char));

insert into my_table select 1 as type, 'x1' as prop_x, 'y1' as prop_y, 'z1' as prop_z from dual union all select 2, 'x2', 'y2', 'z2' from dual union all select 3, 'x3', 'y3', 'z3' from dual union all select 4, 'x4', 'y4', 'z4' from dual; 
commit;

UPD:首先,至少在type仅在(1,2,3,4)中的情况下,我需要解决方案

2 个答案:

答案 0 :(得分:0)

您可以使用条件聚合:

select max(case when type = 1 then prop_x end) as prop_x_1,
       max(case when type = 2 then prop_x end) as prop_x_2,
       max(case when type = 3 then prop_x end) as prop_x_3,
       max(case when type = 4 then prop_x end) as prop_x_4,
       max(case when type = 1 then prop_y end) as prop_y_1,
       . . .
from my_table;

答案 1 :(得分:0)

使用pivot的解决方案-仅在行数受限的情况下工作(并且以1_prop_x代替prop_x_1加列的顺序与问题不同,但对我来说是可以的):

  select * 
  from 
  (
  select *
  from my_table t
  )
  pivot(
  max(prop_x) as prop_x, max(prop_y) as prop_y, max(prop_z) as prop_z
  for type in (1,2,3,4)
  )