Prepared Statement:交叉表动态mysql查询

时间:2017-01-13 16:09:04

标签: mysql pivot-table crosstab

我正在尝试制作一个交叉表数据透视表。我需要在单独的列上动态地从数据库表中获取所有团队,而不是在我当前正在执行的查询中指定团队的名称。我看了另一个例子,即MySQL pivot table query with dynamic columns

目前我从数据库收到的结果很好,但只能通过在查询中手动输入我需要的列。请参阅以下示例:

SELECT IFNULL(DATE( date_posted ), 'Total') AS DATE, 
SUM(CASE WHEN added_by LIKE '%Team One%' THEN 1 ELSE 0 END) AS Team1, 
SUM(CASE WHEN added_by LIKE '%Team Two%' THEN 1 ELSE 0 END ) AS Team2,
COUNT( added_by ) AS Daily_Total FROM teamdata WHERE status LIKE 
'%completed%' GROUP BY IFNULL(DATE( date_posted ), 'Total') DESC WITH ROLLUP;

显示4列DATE,Team1,Team2和Daily_Total。但是在稍后阶段会添加更多列,但要动态完成。我正在尝试执行这个准备好的声明,但没有成功:

SET @sql = NULL;
SELECT GROUP_CONCAT( DISTINCT 
CONCAT(  
    'sum(CASE WHEN added_by = ''', 
    added_by,  
    ''' THEN 1 else ''-'' END) AS `', added_by,
      '`' 
    ) 
) into @sql 
FROM teamdata;

SET @sql 
= CONCAT('SELECT IFNULL(DATE( date_posted ), \'Total\') AS DATE, ', @sql, ' 
        from teamdata
        WHERE status = \'completed\' 
        GROUP BY IFNULL(DATE( date_posted ), \'Total\') DESC WITH ROLLUP');

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

我能否就此得到进一步的帮助。

0 个答案:

没有答案