如何将一个表结果转换为列sql查询

时间:2016-11-16 05:12:19

标签: mysql sql

我有3张桌子

enter image description here

如何查询此内容以获得此类结果 enter image description here

我可以使用pivot table方法吗? 一个用户可以有n个问题。任何想法

2 个答案:

答案 0 :(得分:0)

您可以使用加入

获取用户的Q1值

JOIN `Question` `Q1` 
     ON `Q1`.`user_id` = `User`.`id` 
        AND `Q1`.`question name` = 'Q1' 

获取用户的Q2值

JOIN `Question` `Q2` 
     ON `Q2`.`user_id` = `User`.`id` 
        AND `Q2`.`question name` = 'Q2' 

查询看起来像这样

SELECT `User`.`id`, 
       `User`.`name`, 
       `Grade`.`grade`, 
       `Q1`.`mark` AS `Q1`, 
       `Q2`.`mark` AS `Q2` 
FROM   `User` 
       JOIN `Grade` 
         ON `User`.`id` = `Grade`.`user_id` 
       JOIN `Question` `Q1` 
         ON `Q1`.`user_id` = `User`.`id` 
            AND `Q1`.`question name` = 'Q1' 
       JOIN `Question` `Q2` 
         ON `Q2`.`user_id` = `User`.`id` 
            AND `Q2`.`question name` = 'Q2' 

enter image description here

答案 1 :(得分:0)

此查询会将您的数据行转换为您的问题数据的别名为Question name的列

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(IF(`Question name` = "', `Question name`, '",`mark`,NULL)) as ', `Question name`)
  ) INTO @sql
FROM Question;

SET @sql = CONCAT('SELECT `User`.`id`, `User`.`name`, `Grade`.`grade`, ', @sql, ' 
                  FROM `User` join `Grade` on `User`.`id` = `Grade`.`user_id` 
                  join `Question` on `User`.`id` = `Question`.`user_id` GROUP BY `User`.`id`');

PREPARE stmt FROM @sql;
EXECUTE stmt;

User table Grade table Question table Result of the query

SQL Fiddle