mysql按月分组并补齐

select
    a.month,
    IFNULL(b.point_count_0, 0) as point_count_0,
    IFNULL(b.point_count_1, 0) as point_count_1,
    IFNULL(b.point_count_2, 0) as point_count_2,
    IFNULL(b.point_count_3, 0) as point_count_3
from
    (
    select
        DATE_FORMAT(CURDATE(), '%Y-%m') as month
union
    select
        DATE_FORMAT(CURDATE() - interval 1 month, '%Y-%m') as month
union
    select
        DATE_FORMAT(CURDATE() - interval 2 month, '%Y-%m') as month
union
    select
        DATE_FORMAT(CURDATE() - interval 3 month, '%Y-%m') as month
union
    select
        DATE_FORMAT(CURDATE() - interval 4 month, '%Y-%m') as month
union
    select
        DATE_FORMAT(CURDATE() - interval 5 month, '%Y-%m') as month
union
    select
        DATE_FORMAT(CURDATE() - interval 6 month, '%Y-%m') as month
union
    select
        DATE_FORMAT(CURDATE() - interval 7 month, '%Y-%m') as month
union
    select
        DATE_FORMAT(CURDATE() - interval 8 month, '%Y-%m') as month
union
    select
        DATE_FORMAT(CURDATE() - interval 9 month, '%Y-%m') as month
union
    select
        DATE_FORMAT(CURDATE() - interval 10 month, '%Y-%m') as month
union
    select
        DATE_FORMAT(CURDATE() - interval 11 month, '%Y-%m') as month
        ) a
left join (
    select
        DATE_FORMAT(jsrp.create_time, '%Y-%m') as month,
        count(jsrg.grade_code = '64b73c51de18904e31ee3365' or null) as point_count_0,
        count(jsrg.grade_code = '64b73c5ede18904e31ee3366' or null) as point_count_1,
        count(jsrg.grade_code = '64b73c78de18904e31ee3367' or null) as point_count_2,
        count(jsrg.grade_code = '64b73c78de18904e31ee3368' or null) as point_count_3
    from
        jld_safe_risk_point jsrp
    left join jld_safe_risk_grade jsrg 
        on
        jsrp.grade_code = jsrg.grade_code
    where
        DATE_FORMAT(jsrp.create_time, '%Y-%m') > DATE_FORMAT(DATE_SUB(CURDATE(), interval 12 month), '%Y-%m')
    group by
        month
            ) b
            on
    a.month = b.month
order by
    a.month asc
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值