I am trying to dynamically pivot the key value pairs in the table below.
+-----------------+-----------------------------+-------+
| id | category | name | value |
+-----------------+-----------------------------+-------+
| 1 | acme | 2fa | 0 |
| 2 | acme | abc_processing_date | today |
| 3 | acme | activate_new_approve_person | 1 |
| 4 | acme | activate_new_schdule | 1 |
| 5 | acme | additional_footer_for_person| NULL |
+-----------------+-----------------------------+-------+
Running my query below I am getting the error
'-new-schedule,IFNULL(IF(z_tmp_admin_system_settings.name = 'additional_footer_fo' at line 1
I this developed using method described by Taryn in MySQL pivot table query with dynamic columns .
SET SESSION group_concat_max_len = 100000;
SET @sql = '';
SELECT GROUP_CONCAT(DISTINCT
CONCAT(
'IFNULL(IF(z_tmp_admin_system_settings.name = ''',
name,
''', value, NULL), NULL) AS ',
name
)
)
INTO @sql
FROM z_tmp_admin_system_settings;
SET @sql = CONCAT('SELECT subdomain, ', @sql, ' FROM name GROUP BY subdomain');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
There are several problems with your code - by descreasing gravity:
from z_tmp_admin_system_settings
, not from name
category
, not subdomain
MAX()
; old versions of MySQL tolerate not using an aggregate function on non-aggregated columns, but that's not something to get accustomed toDISTINCT
is probably not needed, unless you have duplicated name
s per category (in this case, feel free to add it back to the below code) IFNULL(..., NULL)
is a no-opCode:
SET SESSION group_concat_max_len = 100000;
SET @sql = '';
SELECT GROUP_CONCAT(
CONCAT('MAX(IF(z_tmp_admin_system_settings.name = ''', name, ''', value, NULL)) AS `', name, '`')
)
INTO @sql
FROM z_tmp_admin_system_settings;
SET @sql = CONCAT(
'SELECT category, ',
@sql,
' FROM z_tmp_admin_system_settings GROUP BY category'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
| category | 2fa | abc_processing_date | activate_new_approve_person | activate_new_schdule | additional_footer_for_person |
| -------- | --- | ------------------- | --------------------------- | -------------------- | ---------------------------- |
| acme | 0 | today | 1 | 1 | |
It looks like some of your names have hyphens in them; one of them ends with -new-schedule
(although the sample data posted has activate_new_schedule
-- is that accurate?). You need to enclose the names in backticks to escape these names when using them as aliases.
SELECT GROUP_CONCAT(DISTINCT
CONCAT(
'IFNULL(IF(z_tmp_admin_system_settings.name = ''',
name,
''', value, NULL), NULL) AS `',
name,
'`'
)
)
INTO @sql
FROM z_tmp_admin_system_settings;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.