”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何将MySQL表格数据与问题答案作为列旋转?

如何将MySQL表格数据与问题答案作为列旋转?

发布于2025-03-23
浏览:964

How to Pivot MySQL Table Data with Question Answers as Columns?
mySQL pivot Table Data AS ROWS

To convert the given data into a pivot table format, where question answers are displayed as columns, the following query can be used:SELECT a.ID, a.user_id, A.job_id, max(c.question ='是这个吗?'然后b.answer end) max(c.question ='或this的情况? max(c.question ='or that?'然后b.answer end)还是那个? ' 从结果a 内部加入答案b 在a.id上= b.fk_result_id 内在加入问题c 在b.fk_question_id = c.id上 a.id的组 a.user_id, a.job_id

在此查询中,案例表达式用于检查问题表的问题列,并从答案表返回相应的答案。然后,使用最大的聚集函数来找到每个问题的最大值,这表示为该问题提供的答案。

动态互动

对于未知或大型语句的情况,可以使用下面的SQL语句生成以下代码: 选择 group_concat(不同 concat( 'max(c.question =''',情况 问题, ''然后b.answer end) concat(''',问题,''') ) )进入@sql 提问; set @sql = concat('select a.id, a.user_id, a.job_id,',@sql,' 从结果a 内部加入答案b 在a.id上= b.fk_result_id 内在加入问题c 在b.fk_question_id = c.id上 a.id的组 a.user_id, A.job_id'); 从@SQL准备STMT; 执行STMT; DealLocation准备STMT;

此代码生成一个动态的SQL语句,可以处理任何数量的问题。它通过将每个问题的最大值串联为列名称来动态构造选择子句。
SELECT  a.ID,
        a.user_ID,
        a.job_id,
        MAX(CASE WHEN c.question = 'Is it this?' THEN b.answer END) 'Is it this?',
        MAX(CASE WHEN c.question = 'Or this?' THEN b.answer END) 'Or this?',
        MAX(CASE WHEN c.question = 'Or that? ' THEN b.answer END) 'Or that? '
FROM    Results a
        INNER JOIN Answers b
            ON a.id = b.fk_result_id
        INNER JOIN Question c
            ON b.fk_question_id = c.ID
GROUP   BY a.ID,
        a.user_ID,
        a.job_id
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3