简体   繁体   中英

Dynamic Pivot table columns mysql

I have following tables

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

And I need a query which would give me following result :

test_id  group_id  color  age_group 
1        1         blue   young
2        1         green  middle

I guess we need to use concept of pivot table to get the result, but I am unable to. And I demographic categories can we might be same they tend to change so I need something dynamic so what would be the best way to do it ?

I have tried doing the following based of previous similar questions but it doesn't seems to work for me, here is what I have tried:

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;

Your dynamic SQL is just fine except for one thing. It has an ambiguous column project_id on your second left join, Just replace it with pt.project_id or trd.project_id and it will give desired result.

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;

I ran it on a rextester. Here is the link : dynamic_pivot_test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM