码迷,mamicode.com
首页 > 数据库 > 详细

MySQL 数据底部出现总计字样 第二种办法 纵向合并 20161103

时间:2016-11-03 22:49:00      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:rollup   span   mysql   代码   http   image   png   mysq   money   

上次在博客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

技术分享

 

MySQL 数据底部出现总计字样 第二种办法 纵向合并 20161103

标签:rollup   span   mysql   代码   http   image   png   mysq   money   

原文地址:http://www.cnblogs.com/Mr-Cxy/p/6028584.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!