先查询出日期数据(当前日期往前推12个月)
select bb.date
from (
select @num := @num + 1,date_format(adddate(date_sub(date_sub(curdate(),interval 12 month),interval 1 month),interval @num month), '%Y-%m') as date
from mysql.help_topic,(select @num := 0) as t
where adddate(date_sub(curdate(),interval 12 month),interval @num month) <= date_format(curdate(),'%Y-%m-%d')
order by date
) as bb
group by bb.date
日期数据展示
将上方日期数据作为主表进行查询(查询当前月往前推12个月的数据)
select a.date,ifnull(b.pc_order_price,0) pc_order_price,ifnull(app_order_price,0) app_order_price,ifnull(order_price,0) order_price from
(select bb.date
from (
select @num := @num + 1,date_format(adddate(date_sub(date_sub(curdate(),interval 12 month),interval 1 month),interval @num month), '%Y-%m') as date
from mysql.help_topic,(select @num := 0) as t
where adddate(date_sub(curdate(),interval 12 month),interval @num month) <= date_format(curdate(),'%Y-%m-%d')
order by date
) as bb
group by bb.date) a
left join (
SELECT date,
round((sum(pc_order_price) / 10000),4) pc_order_price,
round((sum(app_order_price) / 10000),4) app_order_price,
round((sum(pc_order_price) / 10000) + (sum(app_order_price) / 10000),4) order_price
FROM
(
SELECT-- f.pay_time,
-- f.invoice_time,
date_format( f.order_time, '%Y-%m' ) AS date,
case when order_mode = 0
then f.order_price
else 0 end pc_order_price,
case when order_mode = 1
then f.order_price
else 0 end app_order_price
FROM
表名 f
WHERE
f.del_flag = 0
AND f.order_time >= date_sub(curdate(),interval 12 month)
) r
GROUP BY
date) b on a.date = b.date;
最终数据展示