首頁 > 資料庫 > mysql教程 > 如何在 MySQL 中建立具有整數列名的動態資料透視表?

如何在 MySQL 中建立具有整數列名的動態資料透視表?

DDD
發布: 2024-11-15 08:40:02
原創
508 人瀏覽過

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.

以上是如何在 MySQL 中建立具有整數列名的動態資料透視表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板