如何使用整數使用者 ID 在 MySQL 中建立動態資料透視表?

Mary-Kate Olsen
發布: 2024-11-14 16:13:02
原創
336 人瀏覽過

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.

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

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