我有一个数据表,其中一些数据如下所示。
Table name Uk_Small_Stage1
name created 1m
IA UK Smaller Companies 17/10/2017 3.9
Jupiter UK Smaller Companies I Acc 17/10/2017 6.96
Old Mutual UK Smaller Companies Focus R Inc GBP 17/10/2017 2.19
TB Amati UK Smaller Companies B Acc 17/10/2017 4.85
TM Cavendish AIM B 17/10/2017 2.34
我希望将表格转换为
Created IA UK Smaller Companies Jupiter UK Smaller Companies I Acc Old Mutual UK Smaller Companies Focus R Inc GBP
17/10/2017 3.9 6.96 2.19
(对于字段" name"。
,每行应显示一列Uk_Small_Stage1每个日期都有多条记录。
我正在尝试使用下面的代码,它应该动态构建并执行数据库,但是我遇到了mysql错误。
请问有人帮忙吗?
SET group_concat_max_len=2048;
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(name = ''',
name,
''', 1m, NULL)) AS ‘,
CONCAT("`”,name,"`")
)
)
) INTO @sql
FROM UK_Small_Stage1;
SET @sql = CONCAT('SELECT created, ', @sql, ' FROM UK_Small_Stage1 GROUP BY created’);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
最新代码
SET group_concat_max_len=2048;
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(name = ''',
name,
''', 1m, NULL)) AS ‘,
CONCAT(''',name,''')
)
)
) INTO @sql
FROM UK_Small_Stage1;
SET @sql = CONCAT('SELECT created, ', @sql, ' FROM UK_Small_Stage1 GROUP BY created’);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;