Twój dynamiczny SQL jest w porządku, z wyjątkiem jednej rzeczy. Ma niejednoznaczną kolumnę project_id
na drugim sprzężeniu po lewej, po prostu zastąp go pt.project_id
lub trd.project_id
i da pożądany rezultat.
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;
Uruchomiłem to na rextesterze. Oto link :dynamic_pivot_test