将列反转为行 - PL/ SQL
Unpivot coumns into rows - PL/ SQL
我有以下 table - 有很多行 -
ID A_1 B_1 A_2 B_2 A_3 B_3
-- ---- --- --- ---- --- ---
1 0 0 0 0 0 0
2 1 0 0 0 0 0
我需要获得以下输出 table -
这些行将是 ID,A_1,B_1 等等。
ID A B
--- -- --
1 0 0
1 0 0
1 0 0
2 1 0
2 0 0
2 0 0
我尝试使用 union, unpivot - 每个 ID 只得到一行而不是三行。
我该怎么做?
您必须使用 Union all 来包含重复项:
结果:
SELECT ID, A_1 A, B_1 B FROM TABLE1
UNION ALL
SELECT ID, A_2, B_2 FROM TABLE1
UNION ALL
SELECT ID, A_3, B_3 FROM TABLE1 ORDER BY ID;
select *
from t
unpivot (
(A,B)
for z in (
(A_1, B_1),
(A_2 , B_2),
(A_3, B_3)
)
);
带有结果的完整测试用例:
with t (ID, A_1, B_1, A_2 , B_2 , A_3, B_3) as (
select 1, 0 , 0, 0, 0, 0, 0 from dual union all
select 2, 1 , 0, 0, 0, 0, 0 from dual
)
select *
from t
unpivot (
(A,B)
for z in (
(A_1, B_1),
(A_2 , B_2),
(A_3, B_3)
)
);
结果:
ID Z A B
---------- ------- ---------- ----------
1 A_1_B_1 0 0
1 A_2_B_2 0 0
1 A_3_B_3 0 0
2 A_1_B_1 1 0
2 A_2_B_2 0 0
2 A_3_B_3 0 0
我有以下 table - 有很多行 -
ID A_1 B_1 A_2 B_2 A_3 B_3
-- ---- --- --- ---- --- ---
1 0 0 0 0 0 0
2 1 0 0 0 0 0
我需要获得以下输出 table -
这些行将是 ID,A_1,B_1 等等。
ID A B
--- -- --
1 0 0
1 0 0
1 0 0
2 1 0
2 0 0
2 0 0
我尝试使用 union, unpivot - 每个 ID 只得到一行而不是三行。
我该怎么做?
您必须使用 Union all 来包含重复项:
结果:
SELECT ID, A_1 A, B_1 B FROM TABLE1
UNION ALL
SELECT ID, A_2, B_2 FROM TABLE1
UNION ALL
SELECT ID, A_3, B_3 FROM TABLE1 ORDER BY ID;
select *
from t
unpivot (
(A,B)
for z in (
(A_1, B_1),
(A_2 , B_2),
(A_3, B_3)
)
);
带有结果的完整测试用例:
with t (ID, A_1, B_1, A_2 , B_2 , A_3, B_3) as (
select 1, 0 , 0, 0, 0, 0, 0 from dual union all
select 2, 1 , 0, 0, 0, 0, 0 from dual
)
select *
from t
unpivot (
(A,B)
for z in (
(A_1, B_1),
(A_2 , B_2),
(A_3, B_3)
)
);
结果:
ID Z A B
---------- ------- ---------- ----------
1 A_1_B_1 0 0
1 A_2_B_2 0 0
1 A_3_B_3 0 0
2 A_1_B_1 1 0
2 A_2_B_2 0 0
2 A_3_B_3 0 0