mysql按照时间统计数据

1、按天进行统计

数据库时间格式

·
在这里插入图片描述

SELECT DATE_FORMAT(`字段名`, '%Y-%m-%d') AS days,COUNT(1) AS num FROM 表名
GROUP BY days;

%Y-%m-%d格式一定要和数据库时间格式对应

2、按小时统计

SELECT DATE_FORMAT(`字段名`, '%Y-%m-%d %H') AS days,COUNT(1) AS num FROM 表名
GROUP BY days;

3、按分统计

SELECT DATE_FORMAT(`字段名`, '%Y-%m-%d %H:%i') AS days,COUNT(1) AS num FROM 表名
GROUP BY days;

4、按秒统计

SELECT DATE_FORMAT(`字段名`, '%Y-%m-%d %H:%i:%S') AS days,COUNT(1) AS num FROM 表名
GROUP BY days;

5、按天查询数据

select * from itops_message_center where  DATE_FORMAT(publish_time,'%Y-%m-%d') = '2022-06-14'

6、统计本周数据及对应个数

SELECT DATE_FORMAT(createtime, '%Y-%m-%d') dateTime,
count(1) countNumber
FROM aa
WHERE YEARWEEK(date_format(createtime, '%Y-%m-%d')) = YEARWEEK(now())
GROUP BY dateTime;

7、统计本周数据及对应个数,没有的自动补0

select
       d.date, IFNULL(T.countNumber, 0) countNumber
from (
         select date_sub(curdate(), INTERVAL WEEKDAY(curdate()) + 0 DAY) as date
         UNION ALL
         select date_sub(curdate(), INTERVAL WEEKDAY(curdate()) - 1 DAY) as date
         UNION ALL
         select date_sub(curdate(), INTERVAL WEEKDAY(curdate()) - 2 DAY) as date
         UNION ALL
         select date_sub(curdate(), INTERVAL WEEKDAY(curdate()) - 3 DAY) as date
         UNION ALL
         select date_sub(curdate(), INTERVAL WEEKDAY(curdate()) - 4 DAY) as date
         UNION ALL
         select date_sub(curdate(), INTERVAL WEEKDAY(curdate()) - 5 DAY) as date
         UNION ALL
         select date_sub(curdate(), INTERVAL WEEKDAY(curdate()) - 6 DAY) as date
     ) d
         left join(
    select
          DATE_FORMAT(createtime, '%Y-%m-%d') dateTime,
               COUNT(1)                            countNumber
    from aa
    group by DATE_FORMAT(createtime, '%Y-%m-%d')
) T on T.dateTime = d.date
GROUP BY d.date;

8、统计当月的数据

select DATE_FORMAT(createtime, '%Y-%m-%d') dateTime,
count(1) countNumber
    from aa
where
    DATE_FORMAT(createtime,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m')
GROUP BY dateTime;

9、统计当月数据,不全的补0

select aa.DAY dateTime,
       (select count(*)
        from task_log t
        where substr(t.createtime, 1, 10) = aa.DAY and t.is_deleted = 0) as countNumber
from (SELECT date_add(DATE_ADD(curdate(), INTERVAL - DAY(curdate()) + 2 DAY),
                      INTERVAL (cast(help_topic_id AS signed INTEGER) - 1) DAY
                 ) DAY
      FROM mysql.help_topic
      WHERE help_topic_id < DAY(last_day(curdate()))
      ORDER BY help_topic_id) aa;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值