今天遇到这样一个问题,要统计某商品最近12个月的销量,输出到UI画个柱状图
sql长这样子:
select date_format(date, '%Y-%m') as month, sum(money) as totalmoney from sales where code='1200040' and date>date_add(last_day(date_sub(curdate(), interval 1 year)), interval 1 day) group by date_format(date, '%Y-%m')
其中date_add(last_day(date_sub(curdate(), interval 1 year)), interval 1 day)是算出12个月前的1号,
比如今天是2018-09-16,则算出的结果是2017-10-01。这样2017-10到2018-09一共12个月
问题来了,有些商品在有些月份就没有销售,上面sql取出来就没有12条。需要补全12条。
思路:先把12个月弄出来,再left join上面的sql
把12个月弄出来的sql如下:
select date_format(date_sub(curdate(), interval t.count month), '%Y-%m') as month from
(
select @counter:=@counter+1 as count from sales, (select @counter:=-1) as t limit 12
) as t
解释:内层sql就是随便拿个表,取12行,再用计数器得到1到12,外层sql是用当前日期减对应的月份数,再格式化成%Y-%m
再把两个sql用left join连起来就行了,最终的sql如下:
select a.month, case when b.totalmoney is null then 0.0 else b.totalmoney end as totalmoney from
(
select date_format(date_sub(curdate(), interval t.count month), '%Y-%m') as month from
(
select @counter:=@counter+1 as count from sales, (select @counter:=-1) as t limit 12
) as t
) as a left join
(
select date_format(date, '%Y-%m') as month, sum(money) as totalmoney from sales where code='1200040' and date>date_add(last_day(date_sub(curdate(), interval 1 year)), interval 1 day) group by date_format(date, '%Y-%m')
) as b on a.month=b.month order by a.month
里面的case when是用来把为null的值变成0.0
这个方案有个缺点是要借助一个至少有12行的表来产生出12个月份。不知道有没有更好的方案直接可以凭空产生出12行来。有解决办法的同学欢迎留言!