【问题标题】:Write dynamic pivot in MYSQL在 MYSQL 中编写动态枢轴
【发布时间】:2021-07-20 17:33:28
【问题描述】:

这是我的数据透视代码。我想把它转换成动态的..

我试过了,显示错误..

SELECT  id,
     GROUP_CONCAT(
         CASE 
             WHEN question.question_name = 'Household'
             THEN answer.text
             ELSE NULL 
         END
     ) AS Household,
     GROUP_CONCAT(
         CASE 
             WHEN question.question_name = 'Dependents' 
             THEN answer.text
             ELSE NULL 
         END
     ) AS Dependents,
     GROUP_CONCAT(
         CASE 
             WHEN question.question_name = 'Generation'
             THEN answer.text
            ELSE NULL 
         END
     ) AS Generation
   
FROM user_answers
inner join answer on user_answers.answer_id=answer.answer_id
inner join question on answer.question_id=question.question_id
GROUP BY id

代码正在运行。我想将其转换为动态转换。我试过。但不工作

SET @sql = NULL;
SELECT
  GROUP_CONCAT(
      'case when question.question_name = ''',
      question.question_name,
      ''' then answer.text ELSE 0  end) AS `',
      question_name, '`'
  ) INTO @sql
FROM  answer
inner join question on answer.question_id=question.question_id;

SET @sql = CONCAT('SELECT id, ', @sql, ' 
                  FROM user_answers
                    inner join answer on user_answers.answer_id=answer.answer_id
                    inner join question on answer.question_id=question.question_id
                    GROUP BY id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

显示错误

PREPARE stmt FROM @sql  Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') AS `Dependents`,case when question.question_name = 'Dependents' then answer.te' at line 1    0.000 sec

【问题讨论】:

  • 请不要发送垃圾标签,他们会为您的问题收集正确的受众,而不是愤怒的暴徒
  • @RiggsFolly 抱歉

标签: mysql pivot pivot-table mysql-workbench


【解决方案1】:

此博客中的代码将生成所需的查询,然后执行它: http://mysql.rjweb.org/doc.php/pivot

必须使用存储过程——这就是导致您遇到错误的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    相关资源
    最近更新 更多