动态透视表列mysql

jaql4c8m  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(389)

我有以下表格
人口统计和人口分类

demographic_id  demographic_name
1               color
2               age_group

项目测试

test_id  group_id  project_id
1        1         1
2        1         1

测试要求

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;
tuwxkamq

tuwxkamq1#

你的动态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;

我用测试仪测试了一下。这里是链接:动态测试

相关问题