Il tuo SQL dinamico va bene tranne che per una cosa. Ha una colonna ambigua project_id
sul tuo secondo join a sinistra, sostituiscilo con pt.project_id
o trd.project_id
e darà il risultato desiderato.
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when dc.demographic_name = ''',
demographic_name,
''' then trd.demographic_value end) AS ',
replace(demographic_name, ' ', '')
)
) INTO @sql
from demographic_categories;
SET @sql = CONCAT('SELECT pt.test_id, pt.group_id,
', @sql,'
from test_demographic_requirements trd
LEFT JOIN demographic_categories dc ON trd.demographic_id = dc.demographic_id
LEFT JOIN project_tests pt ON pt.test_id = trd.test_id and pt.project_id =1
group by pt.test_id;');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
L'ho eseguito su un rextester. Ecco il link:dynamic_pivot_test