在MySQL中构建动态数据透视查询

时间:2014-09-22 08:57:02

标签: mysql pivot dynamic-pivot

我有这个查询,它有以下输出:

SELECT o.date      AS Date, 
       u.firstname AS FirstName, 
       u.lastname  AS LastName, 
       m.name      AS MealName 
FROM   catering.user u 
       LEFT JOIN catering.order o 
              ON u.iduser = o.iduser 
       LEFT JOIN catering.meal m 
              ON m.idmeal = o.idmeal 
WHERE  o.weeknumber = 37 
GROUP  BY u.firstname, 
          o.date 
ORDER  BY o.date; 

enter image description here

我需要写一个查询来获得以下输出: enter image description here

我关注了与动态数据透视查询相关的其他帖子,但MySql对我来说是一个新主题,我无法弄清楚如何在我的情况下使用预准备语句?

我得到的错误信息是:

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 'NULL' at line 1    

我正在使用MySql Workbench 6.0 CE

1 个答案:

答案 0 :(得分:0)

SET SESSION group_concat_max_len = 1000000;

SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN firstname= ''',
      firstname,
      ''' THEN mealName END) AS ',
      firstname
    )
   )INTO @sql
FROM  
(SELECT o.date      AS Date, 
       u.firstname AS FirstName, 
       u.lastname  AS LastName, 
       m.name      AS MealName 
FROM   catering.user u 
       LEFT JOIN catering.order o 
              ON u.iduser = o.iduser 
       LEFT JOIN catering.meal m 
              ON m.idmeal = o.idmeal 
WHERE  o.weeknumber = 37 
GROUP  BY u.firstname, 
          o.date 
ORDER  BY o.date)x;



SET @sql=CONCAT('SELECT date,',@sql,' FROM
(SELECT o.date      AS Date, 
       u.firstname AS FirstName, 
       u.lastname  AS LastName, 
       m.name      AS MealName 
FROM   catering.user u 
       LEFT JOIN catering.order o 
              ON u.iduser = o.iduser 
       LEFT JOIN catering.meal m 
              ON m.idmeal = o.idmeal 
WHERE  o.weeknumber = 37 
GROUP  BY u.firstname, 
          o.date 
ORDER  BY o.date)x  
GROUP BY date');


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

FIDDLE