将展平的单行转换为多行 Oracle SQL
Convert a flattened single row into multiple rows Oracle SQL
我有一个数据库 table,它基本上将 'poll question' 维度扁平化为 table,每个问题有 1 列。
例如:这些是 table 中的列:
POLL1_QUESTION
POLL1_ANSWER
POLL2_QUESTION
POLL2_ANSWER
POLL3_QUESTION
POLL3_ANSWER
我想要做的是将每一行映射到一个新的 table 中,如下所示:
QUESTION_NUMBER
QUESTION
ANSWER
在我的用例中甚至不需要问题编号列,但它会很好。
是否可以将这 1 行 6 列转换为 3 行 2 列?
如果您使用的是 Oracle 数据库 11g 或更高版本,您想使用 UNPIVOT
:
select *
from your_table
unpivot (
(question, answer)
for question_id in (
(question1, answer1) as 1,
(question2, answer2) as 2,
(question3, answer3) as 3
)
);
对于 Oracle 11g 之前的版本,使用 case
(或 decode
):
select
n as question_id,
case n
when 1 then question1
when 2 then question2
when 3 then question3
end as question,
case n
when 1 then answer1
when 2 then answer2
when 3 then answer3
end as answer
from your_table
cross join (
select level as n
from dual
connect by level <= 3
) x;
我有一个数据库 table,它基本上将 'poll question' 维度扁平化为 table,每个问题有 1 列。
例如:这些是 table 中的列:
POLL1_QUESTION
POLL1_ANSWER
POLL2_QUESTION
POLL2_ANSWER
POLL3_QUESTION
POLL3_ANSWER
我想要做的是将每一行映射到一个新的 table 中,如下所示:
QUESTION_NUMBER
QUESTION
ANSWER
在我的用例中甚至不需要问题编号列,但它会很好。
是否可以将这 1 行 6 列转换为 3 行 2 列?
如果您使用的是 Oracle 数据库 11g 或更高版本,您想使用 UNPIVOT
:
select *
from your_table
unpivot (
(question, answer)
for question_id in (
(question1, answer1) as 1,
(question2, answer2) as 2,
(question3, answer3) as 3
)
);
对于 Oracle 11g 之前的版本,使用 case
(或 decode
):
select
n as question_id,
case n
when 1 then question1
when 2 then question2
when 3 then question3
end as question,
case n
when 1 then answer1
when 2 then answer2
when 3 then answer3
end as answer
from your_table
cross join (
select level as n
from dual
connect by level <= 3
) x;