Home > Database > Mysql Tutorial > How to Create a Dynamic Pivot Table in MySQL with Integer User IDs?

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

DDD
Release: 2024-11-12 22:59:02
Original
439 people have browsed it

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

Dynamic Pivot Table in MySQL

When working with a database, it is often useful to create pivot tables to summarize data across multiple columns. However, when the column names are dynamic, it can present a challenge. This article explores how to create a dynamic pivot table in MySQL, particularly when the user IDs are integers.

In the example provided by the user, the query failed when the user ID was an integer, but worked fine when it was a string. The issue arose because the values were being used as column names directly. To resolve this, it is necessary to wrap the values in backticks (`) to create valid column names.

For instance, instead of:

max(case when user_id = 1 then score end) as 1
Copy after login

The corrected syntax would be:

max(case when user_id = 1 then score end) as `1`
Copy after login

Additionally, when selecting the columns dynamically, the backticks must also be included. The corrected query would look like:

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;
Copy after login

By making these adjustments, the pivot table can be generated successfully, even when the user IDs are integers.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template