I am trying to make a cross tab pivot table. I need to get all teams from the database table dynamically on separate columns instead of specifying names of the teams in the query which I am currently doing. I have looked at another example i.e. MySQL pivot table query with dynamic columns.
At the moment I am receiving the results fine from the database but only by manually typing what column I need in the query. See the example below:
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;
Which displays 4 columns of DATE, Team1, Team2 and Daily_Total. But at a later stage there will be more columns to add in but to be done dynamically. I am trying to execute this prepared statement but to no success:
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;
Please could I get further help on this.