Dynamic Pivot table columns mysql

后端 未结 1 1850
情深已故
情深已故 2021-01-21 02:07

I have following tables

demographic_categories

demographic_id  demographic_name
1               color
2               age_group
<         


        
1条回答
  •  一整个雨季
    2021-01-21 02:35

    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

    0 讨论(0)
提交回复
热议问题