使用count(*)创建动态数据透视表查询mysql

时间:2014-12-13 19:27:14

标签: mysql sql report pivot

我想尝试这样的结果集:

chartday    username    [number of results]
2014-12-12  person3 73
2014-12-12  person2 9
2014-12-12  person4 166
2014-12-12  person1 103
2014-12-12  person5 1
2014-12-12  person6 168

2014-12-13  person2 15
2014-12-13  person7 22
2014-12-13  person1 119

我希望结果如下:

chartday   person1 person2 person3 person4 person5 person6 person7
2014-12-12 103     9       73      166     1       168     0
2014-12-13 119     15      0       0       0       0       22

我正在使用mySQL并且已经在这方面工作了一段时间并且想要一些想法。以下是我一直在使用的示例:SQLFiddle,但我无法弄清楚如何添加count(*)来返回信息。

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合:

SELECT chartday
      ,MAX(CASE WHEN username = 'person1' THEN CT ELSE 0 END) AS Person1
      ,MAX(CASE WHEN username = 'person2' THEN CT ELSE 0 END) AS Person2
      ,MAX(CASE WHEN username = 'person3' THEN CT ELSE 0 END) AS Person3
      ,MAX(CASE WHEN username = 'person4' THEN CT ELSE 0 END) AS Person4
      ,MAX(CASE WHEN username = 'person5' THEN CT ELSE 0 END) AS Person5
      ,MAX(CASE WHEN username = 'person6' THEN CT ELSE 0 END) AS Person6
      ,MAX(CASE WHEN username = 'person7' THEN CT ELSE 0 END) AS Person7
FROM Table1
GROUP BY chartday

演示:SQL Fiddle

为了使这个动态,您必须使用预准备语句:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(IF(username = ''',
      username,
      ''', ct, 0)) AS ',
      username
    )
  ) INTO @sql
FROM Table1;
SET @sql = CONCAT('SELECT chartday, ', @sql, ' FROM Table1 GROUP BY chartday');

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

演示:SQL Fiddle2