MySQL中统计一天之内每个时间段内的数据,很急
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL中统计一天之内每个时间段内的数据,很急相关的知识,希望对你有一定的参考价值。
有两个表
表一:粉丝表Fans
表二:粉丝统计表Fanstrack
要求
Fanstrack 统计 从fans表里面拿取数据
Total (subscribe=1)的所有的粉丝数据的总和
New (subscribe=1) 所有新增粉丝数据的总和
outflow (subscribe=0) 所有流失流失粉丝数据的总和
net 用new - outflow 净增粉丝的总和
(subscribe=1)关注的粉丝
(subscribe=0)取消关注的粉丝
(uid) 被关注的对象
按时间段(两个小时一个时间段)进行统计,定时插入到粉丝统计表里面,如果按天统计的话,通过存储过程和定时器可以实现,我这里有个sql语句
INSERT INTO yht_fanstrack(total,new,outflow,net,time,uid)
SELECT c.total,a.new,b.outflow,(a.new-b.outflow) AS net,a.time,a.uid FROM
(SELECT now() AS time,COUNT(subscribe_time) AS new,uid FROM yht_fans WHERE subscribe_time>=UNIX_TIMESTAMP(CURDATE()) and subscribe_time<=UNIX_TIMESTAMP(CURDATE())+86400 GROUP BY uid) a
JOIN
(SELECT now() AS time,COUNT(cancel_time) AS outflow,uid FROM yht_fans WHERE cancel_time>=UNIX_TIMESTAMP(CURDATE()) and cancel_time<=UNIX_TIMESTAMP(CURDATE())+86400 GROUP BY uid) b
ON
a.uid=b.uid
JOIN
(SELECT COUNT(subscribe) AS total,uid FROM yht_fans GROUP BY uid) c
ON
a.uid=c.uid
现在的问题是,按时间段先用sql语句把数据统计出来,然后每天定时自动插入,不知道如何实现。
有没哪位大神给个思路,或者写个实现方案,小弟在此谢过了!!!
select
uid
,CASE WHEN HOUR(subscribe_time) BETWEEN 0 AND 1 THEN '00:00:00'
WHEN HOUR(subscribe_time) BETWEEN 2 AND 3 THEN '02:00:00'
...
ELSE '23:00:00' END -- 生成时间分层部分,insert前外层sql加上日期后作为唯一的时间值
,COUNT(*)
FROM yht_fans WHERE subscribe_time>=UNIX_TIMESTAMP(CURDATE()) and subscribe_time<=UNIX_TIMESTAMP(CURDATE())+86400
GROUP BY 1,2本回答被提问者采纳 参考技术B @param pay_time数据库时间戳字段
@param price_transaction数据库价格字段
$date = '2018-09-21';
$sql = "
SELECT
HOUR (FROM_UNIXTIME(pay_time)) AS Hour,
sum(price_transaction) as sum
FROM
zt_order
WHERE
FROM_UNIXTIME(pay_time, '%Y-%m-%d') = '$date'
GROUP BY
HOUR (FROM_UNIXTIME(pay_time))
ORDER BY
HOUR (FROM_UNIXTIME(pay_time))
";
$query = $this->db->query($sql);
$data = $query->result_array();
返回每个小时对应的和
不足的地方在于如果该时间段数据为0,则不返回数据
从日志文件中统计给定时间段内的唯一用户数
Sample log line:[INFO] 2009-03-06 20:47:35 | controller::bla | user: vincentvega | ip: 127.0.0.1
cat xyz.log | grep "2009-03" | ruby -ne 'puts $1 if $_ =~ /user:s(w+)/' | sort -u | wc -l
以上是关于MySQL中统计一天之内每个时间段内的数据,很急的主要内容,如果未能解决你的问题,请参考以下文章