我是 php 和 mysql 的新手,我正在尝试使用下面的代码创建交叉表查询:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('SUM(IF(category = ''',category,''', duration,NULL))AS ',category)) INTO @sql
FROM tblnon_oeedata;
SET @sql = CONCAT('SELECT productionDay, ', @sql, ' FROM tblnon_oeedata GROUP BY productionDay');
PREPARE stmt FROM @sql;
EXECUTE stmt;
每次运行它时,我都会收到错误:
#1064
- You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Maintenance During Production,SUM(IF(category = 'Breakdowns', duration,NULL))AS ' at line 1
如何解决这个问题,我真的很困惑。提前致谢
最佳答案
试试这个:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('SUM(IF(category = ''',category,''', duration,NULL))AS ''',category, '''')) INTO @sql
FROM tblnon_oeedata;
SET @sql = CONCAT('SELECT productionDay, ', @sql, ' FROM tblnon_oeedata GROUP BY productionDay');
PREPARE stmt FROM @sql;
EXECUTE stmt;
关于mysql - 使用 mysql 创建交叉表查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20755759/