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.111cn.netFROM tb_user_online_logWHERE create_time >1395046800 AND create_time<1395061200GROUP BY `date`ORDER BY create_time |
结果如下
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_logGROUP BY hoursORDER BY create_time |
结果如下 www.111cn.net
注意:case when 效率不高,在数据量大时不推荐使用,这里仅列出解决方案,仅供参原文来自: