mysql 按月統計可是有幾個月沒有數據,須要變成0

建立如今倒過去的12個月的視圖sql

CREATE VIEW `past_12_month_view` AS
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`ast

寫出本身的sqlclass

SELECT DATE_FORMAT(create_date,'%Y-%m') as paTime,COUNT(a.create_date) as xunNum from patrol_record a GROUP BY paTime /*平常巡查*/date

 

左連接select

select t.month as paTime,
ifNull(b.xunNum,0) as xunNum from past_12_month_view t LEFT JOIN
(SELECT DATE_FORMAT(create_date,'%Y-%m') as paTime,COUNT(a.create_date) as xunNum from patrol_record a GROUP BY patime) b
on b.paTime=t.month /*平常巡查*/im

 

相關文章
相關標籤/搜索