使用下面的MySQL查询,我创建了一个数据透视表,这正是我正在寻找的。但是,我想用实际描述替换NULL值,例如SubTotal和GrandTotal。这是我的PHP输出上显示的数据透视表格式(希望格式化有点清晰!)。
Name Division 1 Division 2 Division 3 Division 4 Location
Name 1
Name 2
Name 3
NULL Total Total Total Total
Name 4
Name 5
NULL Total etc
NULL Column Grand Total
这是我用来生成表的查询。在研究了这个问题后,CASE功能似乎就是这样。但是,当我将两个CASE行添加到下面的查询中时,它似乎不想工作。返回的mysql_error表示“GROUPING函数不存在”。
SELECT
CASE WHEN (GROUPING(name)=1) THEN 'MainTotal' ELSE name END AS name,
CASE WHEN (GROUPING(location)=1) THEN 'SubTotal' ELSE location END AS location,
name AS Name,
SUM(IF(division='OEM',totalHours,NULL)) AS OEM,
SUM(IF(division='A/M',totalHours,NULL)) AS AM,
SUM(IF(division='SKF',totalHours,NULL)) AS SKF,
SUM(IF(division='RE',totalHours,NULL)) AS RE,
location as Location
FROM $databasetable GROUP BY location, name
WITH ROLLUP
有谁能告诉我我做错了什么? CASE函数是否可以替换NULL类别标题?
提前致谢!
答案 0 :(得分:12)
试试这样:
SELECT
IFNULL(name, 'MainTotal') AS name,
IFNULL(location, 'SubTotal') AS location,
SUM(IF(division='OEM',totalHours,NULL)) AS OEM,
SUM(IF(division='A/M',totalHours,NULL)) AS AM,
SUM(IF(division='SKF',totalHours,NULL)) AS SKF,
SUM(IF(division='RE',totalHours,NULL)) AS RE,
location as Location
FROM $databasetable GROUP BY location, name
WITH ROLLUP
答案 1 :(得分:0)
我知道这个问题在这一点上相当陈旧,但结果仍然是我在Google搜索“带汇总标签的mysql”时返回的第一个问题。
您的回复使用grouping()
函数,该函数不属于MySQL,但有类似的方法可以解决您的问题。
我假设你试图避免在执行后调整查询的输出。
尝试以下方法:
SELECT
CASE
WHEN [column1 grouped by] IS NULL THEN "Total"
ELSE [column1]
END AS `[alias]`,
CASE
WHEN [column1 grouped by] IS NULL THEN "---"
ELSE [column2]
END AS `[alias2]`,
SUM(IF([condition1] = [variable], [sum column], 0)) as `[alias3]`
...
FROM [table]
GROUP BY [column1] WITH ROLLUP
此处的逻辑替换为按组分组返回的空值,使用ROLLUP
时最后一行会出现该值。汇总未汇总的任何其他列默认为查询返回的最后一行,不包括汇总总计。为避免这种情况,您可以使用大小写来检查按列分组是否为空,并通过大小写返回将所选列值替换为您希望的值。
如果您需要进行小计,请使用相同的逻辑,但设置查询的单独实例并将它们UNION
组合在一起以形成数据透视表。