2

我试图让一个带有动态列的数据透视表工作。当 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

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

谢谢

4

2 回答 2

2

由于值在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

于 2013-07-21T14:12:51.447 回答
1

确实很简单 - 仅数字不是 SQL 中的有效列名,因此您需要修改代码以将它们括在反引号中:

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;

我建议对字符串值也保留此更改,以防您的某些字符串值与保留字匹配或包含空格。

(此外,'数字值不需要,因此我已将它们从 case 子句中删除。)

SQLFiddle在这里

于 2013-07-21T14:12:55.873 回答