我有以下表格
demographic_categories
demographic_id demographic_name
1 color
2 age_group
project_tests
test_id group_id project_id
1 1 1
2 1 1
test_demographic_requirements
test_id project_id demgraphic_id demographic_value
1 1 1 blue
1 1 2 young
2 1 1 green
2 1 2 middle
我需要一个查询,它会给我以下结果:
test_id group_id color age_group
1 1 blue young
2 1 green middle
我想我们需要使用数据透视表的概念来获得结果,但我无法做到。而我的人口统计类别可能会相同,他们往往会改变,所以我需要一些动态的东西,那么最好的方法是什么呢?
我尝试过根据以前的类似问题做以下事情,但它似乎对我不起作用,这是我尝试过的:
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_requirement_demographic 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 project_id =1
group by pt.test_id;');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
答案 0 :(得分:2)
除了一件事,你的动态SQL就好了。它在您的第二个左连接中有一个不明确的列project_id
,只需将其替换为pt.project_id
或trd.project_id
,它就会得到所需的结果。
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;
我在rextester上运行它。这是链接:dynamic_pivot_test