我有一个数据库表,基本上扁平了一个民意调查问题'每个问题都有1列的维度。
例如:这些是表格中的列:
POLL1_QUESTION
POLL1_ANSWER
POLL2_QUESTION
POLL2_ANSWER
POLL3_QUESTION
POLL3_ANSWER
我想要做的是将每一行映射到一个新表中,如下所示:
QUESTION_NUMBER
QUESTION
ANSWER
问题编号栏在我的用例中甚至不是必需的,但它会很好。
是否可以将这1行包含6列而不是3行2列?
答案 0 :(得分:4)
如果您使用的是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;