Home >Database >Mysql Tutorial >How to Create Dynamic Pivot Tables with Integer Column Names in MySQL?

How to Create Dynamic Pivot Tables with Integer Column Names in MySQL?

DDD
DDDOriginal
2024-11-15 08:40:02488browse

How to Create Dynamic Pivot Tables with Integer Column Names in MySQL?

Dynamic Pivot Tables in MySQL

When attempting to generate a pivot table with dynamic columns, it is crucial to ensure that the column names are handled correctly. In the provided situation, the user_id is an integer, which can cause issues if not formatted properly.

To address this, it is necessary to wrap the user_id values in backticks (`) to specify them as column names and prevent their misinterpretation as numeric values. Here's the modified 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;

This modification ensures that the user_id values are treated as column names, resulting in a pivot table with dynamic columns representing each unique user_id and their corresponding scores.

The above is the detailed content of How to Create Dynamic Pivot Tables with Integer Column Names in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn