GROUP_CONCAT 中的 COUNT 在查询动态列 table 时不起作用

COUNT in GROUP_CONCAT not working while querying a dynamic column table

我有一个名为 table1 的 table,如下所示:

   id    period         value       name
   1     2020-06-01     3           anna
   2     2020-06-01     2           anna
   3     2020-06-01     3           anna
   4     2020-06-01     1           juned
   5     2020-06-01     3           juned
   6     2020-06-01     2           juned
   7     2020-07-01     3           anna
   8     2020-07-01     2           anna
   9     2020-07-01     2           anna
  10     2020-07-01     3           juned
  11     2020-07-01     3           juned
  12     2020-07-01     3           juned

我希望查询结果显示值的计数 3

name      2020-06-01     2020-07-01
anna          2              2
juned         1              3

我试过这是代码,但它导致错误 #1111 - invalid use of group function

SET @sql = NULL;
SELECT
    GROUP_CONCAT(DISTINCT
        CONCAT(
            'MAX(IF (table1.period = "',
            table1.period, '", COUNT(CASE WHEN value = 3 THEN 1 END), 0)) AS `',
            table1.period, '`'
        )
    ) INTO @sql
FROM table1;
SET @sql =  CONCAT(
                'SELECT name, ',
                @sql,
                ' FROM table1 GROUP BY name'
            ); 
PREPARE stmt FROM @sql;
EXECUTE stmt;

我会把动态 SQL 写成:

SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT 'SUM(value = 3 AND period = ''', period, ''') AS `', period, '`')
INTO @sql
FROM table1;

SET @sql =  CONCAT('SELECT name, ', @sql, ' FROM table1 GROUP BY name'); 
          
-- debug
select @sql;

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

您的代码的主要问题是您在聚合函数中表达条件表达式的方式。另外:

  • 你不需要CONCAT()GROUP_CONCAT()里面:你可以在GROUP_CONCAT()里面放几个值,用字符串分隔

  • 对文字字符串使用单引号而不是双引号

  • DEALLOCATE 执行查询后的语句处理程序

Demo on DB Fiddle - 感谢 Soni 首先创建 fiddle。

生成sql:

| @sql                                                                                                                                                     |
| :------------------------------------------------------------------------------------------------------------------------------------------------------- |
| SELECT name, SUM(value = 3 AND period = '2020-06-01') AS `2020-06-01`,SUM(value = 3 AND period = '2020-07-01') AS `2020-07-01` FROM table1 GROUP BY name |

查询结果:

name  | 2020-06-01 | 2020-07-01
:---- | ---------: | ---------:
anna  |          2 |          1
juned |          1 |          3