Mysql按时间段分组查询来统计会员的个数,mysql个数
Mysql按时间段分组查询来统计会员的个数,mysql个数
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.net
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
结果如下
Mysql按时间段分组查询来统计会员的个数
注意:case when 效率不高,在数据量大时不推荐使用,这里仅列出解决方案,仅供参
mysql 分组之后怎统计记录条数, gourp by 之后的 count
select count(*) from
(SELECT count(*) FROM 表名 WHERE 条件 GROUP BY id ) a ;
mysql 时间分组统计
SELECT date_format(FROM_UNIXTIME( `time`),'%Y-%m-%d') AS time,count(*) as count FROM `表名` WHERE 1 group by time