1. 程式人生 > >MySQL統計過去12個月的資料沒有則為0

MySQL統計過去12個月的資料沒有則為0

查詢每月新增使用者數




celsp_users是使用者表

createTime 為新增使用者時間






SELECT a.count,b.time2 from  
(select count(c.createTime) as count,FROM_UNIXTIME( UNIX_TIMESTAMP(c.createTime),'%m' ) as mon 
from celsp_users c where  FROM_UNIXTIME( UNIX_TIMESTAMP(c.createTime),'%Y' ) = '2015' GROUP BY mon) a 
RIGHT JOIN (SELECT '01' as time2 from  DUAL UNION ALL  
SELECT '02' as time2 from  DUAL UNION ALL 
SELECT '03' as time2 from  DUAL UNION ALL 
SELECT '04' as time2 from  DUAL UNION ALL 
SELECT '05' as time2 from  DUAL UNION ALL 
SELECT '06' as time2 from  DUAL UNION ALL 
SELECT '07' as time2 from  DUAL UNION ALL 
SELECT '08' as time2 from  DUAL UNION ALL 
SELECT '09' as time2 from  DUAL UNION ALL 
SELECT '10' as time2 from  DUAL UNION ALL 
SELECT '11' as time2 from  DUAL UNION ALL 
SELECT '12' as time2 from  DUAL )b on a.mon = b.time2

結果集