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