数据库
首页 > 数据库> > MySQL动态数据透视表

MySQL动态数据透视表

作者:互联网

我试图让动态列的数据透视表工作.当user_id是一个字符串时,它工作正常,但如果它是一个int,那么它似乎失败了

以下是我在过去的问题的帮助下到目前为止的情况:

CREATE TABLE measure2
    (`inspection_date` date, `user_id` int, `score` int, comment text)
;

INSERT INTO measure2
    (`inspection_date`, `user_id`, `score`, comment)
VALUES
    ('2012-10-16', 0, 0, null),
    ('2012-10-16', 1, 0, null),
    ('2012-10-16', 2, 0, null),
    ('2012-10-16', 3, 0, null),
    ('2012-10-17', 0, 1, null),
    ('2012-10-17', 1, 1, null),
    ('2012-10-17', 2, 1, null),
    ('2012-10-18', 3, 1, null)
;


SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when user_id = ''',
      user_id,
      ''' then score end) AS ',
      user_id
    )
  ) INTO @sql
FROM  measure2;

SET @sql = CONCAT('SELECT inspection_date, ', @sql, '
                  FROM measure2
                  GROUP BY inspection_date');

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

见:http://sqlfiddle.com/#!2/eab24/1

我确定它简单,但我错过了什么?

谢谢

解决方法:

由于值是int,你正在使它们成为列名,你必须将值包装在反引号中

sql看起来像:

max(case when user_id = 1 then score end) as `1`

完整查询将是:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when user_id = ''',
      user_id,
      ''' then score end) AS `',
      user_id, '`'
    )
  ) INTO @sql
FROM  measure2;

SET @sql = CONCAT('SELECT inspection_date, ', @sql, ' 
                  FROM measure2 
                  GROUP BY inspection_date');

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

SQL Fiddle with Demo

标签:mysql,pivot-table
来源: https://codeday.me/bug/20190917/1809584.html