我的MySQL数据库有以下列标题:
month, typeOfWork, totalHours
我有兴趣根据typeOfWork和month显示结果.例如,所有typeOfWork条目将显示在左侧的第一列中,并且每个字段将在每个列的指定月份中累计该特定typeOfWork.因此,我的SQL数据透视表语句目前是:
SELECT
IFNULL(typeOfWork, 'Total') AS TypeOfWork,
SUM(IF(month='JAN',totalHours,NULL)) AS JAN,
SUM(IF(month='FEB',totalHours,NULL)) AS FEB,
SUM(IF(month='MAR',totalHours,NULL)) AS MAR,
SUM(IF(month='APR',totalHours,NULL)) AS APR,
SUM(IF(month='MAY',totalHours,NULL)) AS MAY,
SUM(IF(month='JUN',totalHours,NULL)) AS JUN,
SUM(IF(month='JUL',totalHours,NULL)) AS JUL,
SUM(IF(month='AUG',totalHours,NULL)) AS AUG,
SUM(IF(month='SEP',totalHours,NULL)) AS SEP,
SUM(IF(month='OCT',totalHours,NULL)) AS OCT,
SUM(IF(month='NOV',totalHours,NULL)) AS NOV,
SUM(IF(month='DEC',totalHours,NULL)) AS DEC
FROM $databasetable GROUP BY typeOfWork
WITH ROLLUP
我目前收到指定最后一行的语法错误(从’DEC到ROLLUP’).我的困惑来自于我在我的脚本中简单地从另一个工作数据透视表中调整了这个表.我认为差异可能在于我的两个要求(sum totalHours,其中月份等于列名称,而typeOfWork等于第一列中的typeOfWork).我想知道我的IF语句是否需要AND条款?
任何人都可以通过此数据透视表向我指出正确的方向吗?这将不胜感激.谢谢!
解决方法:
您的查询是正确的.
只有一件事–DEC是MySQL reserved word,这个词不能直接用作对象标识符;所以,只需用反引号引用它 –
SELECT
IFNULL(typeOfWork, 'Total') AS TypeOfWork,
SUM(IF(month='JAN',totalHours,NULL)) AS JAN,
...
SUM(IF(month='DEC',totalHours,NULL)) AS `DEC`
FROM $databasetable GROUP BY typeOfWork