我需要旋转桌子。以下是我的疑问。
CREATE TABLE SurveyResponses (
id int,
question varchar(255),
answer varchar(255)
);
INSERT INTO SurveyResponses (id, question, answer) values (1, 'question 1', 'responseX');
INSERT INTO SurveyResponses (id, question, answer) values (2, 'question 1', 'responseY');
INSERT INTO SurveyResponses (id, question, answer) values (3, 'question 1', 'responseZ');
INSERT INTO SurveyResponses (id, question, answer) values (4, 'question 2', 'responseA');
INSERT INTO SurveyResponses (id, question, answer) values (5, 'question 2', 'responseB');
INSERT INTO SurveyResponses (id, question, answer) values (6, 'question 3', 'responseC');
当我尝试使用带有问题的数据透视表作为我得到的列时
<块引用>ORA-00936:缺少表达式
我在查询中遗漏了什么? 我希望它是动态的,因为我在真实表格中有 500 多个问题。
查询
SELECT * FROM (
SELECT id, question, answer from SurveyResponses
) SurveyResponsesResults
PIVOT (
MAX(answer)
FOR question
In(
SELECT DISTINCT question FROM SurveyResponses
)
) As pivottable;
答案 0 :(得分:2)
IN
不能动态。使用第 7 行而不是(注释)第 8 行。
SQL> select * from (
2 select id, question, answer from SurveyResponses
3 ) SurveyResponsesResults
4 PIVOT (
5 max(answer)
6 For question
7 In('question 1' as q1, 'question 2' as q2, 'question 3' as q3
8 --SELECT DISTINCT question FROM SurveyResponses
9 )
10 ) ;
ID Q1 Q2 Q3
---------- ---------- ---------- ----------
1 responseX
6 responseC
2 responseY
4 responseA
5 responseB
3 responseZ
6 rows selected.
SQL>
答案 1 :(得分:0)
扩展@Littlefoot 回答。
如果我必须在 IN
中使用动态输入。
我将不得不使用 PIVOT XML
和 xmlserialize
查询如下。
SELECT xmlserialize(content pivottable.question_XML) from (
SELECT id, question, answer from SurveyResponses
) SurveyResponsesResults
PIVOT XML (
Max(answer)
FOR question
In(
SELECT DISTINCT question FROM SurveyResponses
)
) pivottable ;
查询有效,但以 XML 格式输出。
我想弄清楚如何将 XML 转换为 TABLE。如果您知道,请随时进行编辑。