"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > MySQL Dynamic PivotTable Creation Guide: Integer User ID

MySQL Dynamic PivotTable Creation Guide: Integer User ID

Posted on 2025-04-13
Browse:822

How to Create Dynamic Pivot Tables in MySQL with Integer User IDs?

Pivot Tables in MySQL with Dynamic Columns

This question addresses the challenge of creating MySQL pivot tables with dynamic columns. While the solution works effectively when user_id is defined as a string, it fails when encountering integer values.

The provided code snippet illustrates the initial attempt at creating the pivot table. However, to resolve the issue related to integer user_id values, the corrections lie in the way the column names are constructed within the dynamic SQL query.

The original code:

...
GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when user_id = ''',
      user_id,
      ''' then score end) AS ',
      user_id
    )
  ) INTO @sql

int user_id values are in causing the problem since they are being used directly as column names. To address this, these values need to be wrapped in backticks (`). The corrected code adjusts this:

...
GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when user_id = ''',
      user_id,
      ''' then score end) AS `',
      user_id, '`'
    )
  ) INTO @sql

The final, corrected query:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when user_id = ''',
      user_id,
      ''' then score end) AS `',
      user_id, '`'
    )
  ) INTO @sql
FROM  measure2;

SET @sql = CONCAT('SELECT inspection_date, ', @sql, ' 
                  FROM measure2 
                  GROUP BY inspection_date');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

With these adjustments, the pivot table can now be generated successfully even when dealing with integer user_id values.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3