【问题标题】:ORA-00936: missing expression while using pivotORA-00936: 使用数据透视时缺少表达式
【发布时间】:2021-06-17 02:39:24
【问题描述】:

我需要旋转表格。以下是我的疑问。

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;

【问题讨论】:

    标签: oracle pivot-table


    【解决方案1】:

    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>
    

    【讨论】:

    • 谢谢小脚。但是,如果我有 500 多个问题并且我希望问题文本作为列名,该怎么办。我必须输入所有问题吗?
    【解决方案2】:

    扩展@Littlefoot 答案。

    如果我必须在IN 中使用动态输入。

    我将不得不使用PIVOT XMLxmlserialize 查询如下。

    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。如果您知道,请随时编辑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 2017-08-31
      相关资源
      最近更新 更多