今天碰到个需求需要在log日志表中按照时间段来统计会员的个数,经努力找到了两种解决方案,记录下来以备使用.
1.使用case when方法,不建议使用,代码如下:
- SELECT
- COUNT(DISTINCTuser_id)user_count,
- CASE
- WHENcreate_time>1395046800ANDcreate_time<1395050400THEN'17:00-18:00'
- WHENcreate_time>1395050400ANDcreate_time<1395054000THEN'18:00-19:00'
- WHENcreate_time>1395054000ANDcreate_time<1395057600THEN'19:00-20:00'
- WHENcreate_time>1395057600ANDcreate_time<1395061200THEN'20:00-21:00'
- ELSE'unknown'
- ENDAS`date`www.phpfensi.com
- FROM
- tb_user_online_log
- WHEREcreate_time>1395046800ANDcreate_time<1395061200
- GROUPBY
- `date`
- ORDERBYcreate_time
Mysql按时间段分组查询来统计会员的个数.
2.使用时间戳转换后分组,代码如下:
- SELECT
- COUNT(DISTINCTuser_id)user_count,
- FROM_UNIXTIME(
- create_time,
- '%Y-%m-%d%H:00:00'
- )AShours,
- CONCAT(FROM_UNIXTIME(create_time,'%Y-%m-%d%H:00'),'-',FROM_UNIXTIME(create_time,'%H')+1,":00")AS`date`
- FROM
- tb_user_online_log
- GROUPBY
- hours
- ORDERBYcreate_time