MySQL 数据底部出现总计字样 第二种办法 纵向合并 20161103
上次在博客http://www.cnblogs.com/Mr-Cxy/p/5923375.html
我们使用了group by with rollup 函数 field自定义排序 来实现添加底部总计字样,代码很长,
再有就是我们使用纵向合并 union all 函数 ifnull sum(if())函数来实现纵向合并添加总计字样
SELECT IFNULL(f.城市,"总计") AS 城市,f.7月金额,f.8月金额,f.9月金额 FROM ( SELECT e.* FROM ( SELECT b.城市,SUM(IF(b.年月=201607,b.金额,NULL)) AS 7月金额,SUM(IF(b.年月=201608,b.金额,NULL)) AS 8月金额,SUM(IF(b.年月=201609,b.金额,NULL)) AS 9月金额 FROM ( SELECT city AS 城市,DATE_FORMAT(order_time,"%Y%m") AS 年月,SUM(pay_money) AS 金额 FROM test_a03order AS a GROUP BY city,DATE_FORMAT(order_time,"%Y%m") ) AS b GROUP BY b.城市 ) AS e UNION ALL( SELECT SUM(IF(1=2,0,NULL)) AS 城市,SUM(IF(d.年月=201607,d.金额,NULL)) AS 7月金额,SUM(IF(d.年月=201608,d.金额,NULL)) AS 8月金额,SUM(IF(d.年月=201609,d.金额,NULL)) AS 9月金额 FROM ( SELECT city AS 城市,DATE_FORMAT(order_time,"%Y%m") AS 年月,SUM(pay_money) AS 金额 FROM test_a03order AS c GROUP BY city,DATE_FORMAT(order_time,"%Y%m") ) AS d ) ) AS f