普通分组统计
场景一:根据订单状态统计订单数量。一个很常见,也很简单的统计需求。其中状态字段是订单实体的一个属性
select count(*) count from orders group by status;
场景二:每日统计
-- 统计每日
SELECT DATE_FORMAT(create_date,'%Y-%m-%d') as days, COUNT(id) count FROM order GROUP BY days;
-- 统计每周
SELECT DATE_FORMAT(create_date,'%Y-%u') as weeks, COUNT(id) count FROM order GROUP BY weeks;
-- 统计每月
SELECT DATE_FORMAT(create_date,'%Y-%m') as months, COUNT(id) count FROM order GROUP BY months;
思考:如果其中又一天为空没有数据那么查询时间就有间隔了。如何解决如下
select tmp.days,
case when base.count >0 then base.count else tmp.count end as count
from
(select DATE_ADD('2020-01-01', INTERVAL ( cast( help_topic_id AS signed INTEGER ) + 1 ) DAY) as days,(select 0 ) as count from mysql.help_topic where help_topic_id < DATEDIFF('2022-12-12', '2020-01-01'))
tmp
left join
(select base.* from (SELECT FROM_UNIXTIME(ctime,'%Y-%m-%d') as days, COUNT(id) count FROM orders GROUP BY days) base)
base
on tmp.days = base.days;
进一步思考:获取的数据多少是根据表[ mysql.help_topic]里面数据量的多少来展示,如果在实际开发过程中要设置这个表数据量的大小