Mybatis(MySQL) 查詢過去7天的統計資料,沒有則0補位
阿新 • • 發佈:2021-02-04
例: created: 表中日期欄位 totalCount: 統計的總數 APICallServiceCount: 統計條件1的總數 DataViewServiceCount: 統計條件2的總數 CombinedServiceCount: 統計條件3的總數 apply_category: 條件欄位 SELECT a.created, ifnull( b.totalCount, 0 ) AS totalCount, ifnull( b.APICallService, 0 ) AS APICallServiceCount, ifnull( b.DataViewService, 0 ) AS DataViewServiceCount, ifnull( b.CombinedService, 0 ) AS CombinedServiceCount FROM ( SELECT curdate() AS created UNION ALL SELECT date_sub( curdate(), INTERVAL 1 DAY ) AS created UNION ALL SELECT date_sub( curdate(), INTERVAL 2 DAY ) AS created UNION ALL SELECT date_sub( curdate(), INTERVAL 3 DAY ) AS created UNION ALL SELECT date_sub( curdate(), INTERVAL 4 DAY ) AS created UNION ALL SELECT date_sub( curdate(), INTERVAL 5 DAY ) AS created UNION ALL SELECT date_sub( curdate(), INTERVAL 6 DAY ) AS created ) a LEFT JOIN ( SELECT date ( created ) AS created, count( id ) AS totalCount, SUM( CASE WHEN apply_category = '01' THEN 1 ELSE 0 END ) AS APICallService, SUM( CASE WHEN apply_category = '02' THEN 1 ELSE 0 END ) AS DataViewService, SUM( CASE WHEN apply_category = '03' THEN 1 ELSE 0 END ) AS CombinedService FROM 表名 GROUP BY date ( created ) ORDER BY date ( created ) ASC ) b ON a.created = b.created