MySQL查询按日期范围对结果分组?

编程入门 行业动态 更新时间:2024-10-26 02:32:28
本文介绍了MySQL查询按日期范围对结果分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我得到了一个系统,当他连接应用程序时,它每2到5秒对数据库执行一次ping操作.根据他的连接,ping时间可能会更长,例如10秒左右.

I got a system that pings to the database every 2 to 5 seconds when he is connected the application. Depending on his connection, the ping timeframe can be bigger, like 10 seconds or so.

示例:

Pings: 1,4,6,8,9,12,16,20,50,180,187,189,200,203,206,210 ...

我想运行一个查询以捕获两次ping之间不超过1分钟的范围,将它们分组,这样我就可以知道用户已连接多长时间,并保存到新表中,如:

I want run a query to grab ranges that does not exceed 1 minute between the pings, group them, so I can tell for how long the user has been connected, and save into a new table like:

Connections table: user: X | start_date: 1 | end_date: 50 | duration: 49 user: X | start_date: 180 | end_date: 210 | duration: 30

由于ping从,50、180开始,...超过了1分钟,因此查询组放弃了此操作.

Since the pings from ,50,180, ... that exceeded 1 minute, where disconsidered by the query groups.

ping存储为时间戳,因此可以轻松转换为日期,从最后一次ping到第一次ping的范围将为我提供会话持续时间.

The pings are stored as timestamp, so can be easily converted to date, and the range from the last ping to the first one will give me the session duration.

在MySQL查询中是否有这样做的方法?有帮助吗?

Is there anyway to do it in a MySQL query? Any help?

添加ping历史记录模式

Adding ping history schema

id int(11) user_id int(11) ping_timestamp int(11)

谢谢

推荐答案

我将您给定的示例数据加倍,以显示它如何与多个userId一起使用.

I doubled your given sample data to show how it works with multiple userIds.

在sqlfiddle中实时查看它的运行情况此处.

See it working live in an sqlfiddle here.

select userid, groupnum, min(ping) as start_date, max(ping) as end_date, max(ping) - min(ping) as duration from ( select *, @groupnum := if(@prevUser != userId, @groupnum + 1, @groupnum), @groupnum := if(ping - @prevTS > 60, @groupnum + 1, @groupnum) as groupnum, @prevUser := userid, @prevTS := ping from Table1 t , (select @groupnum:=1, @prevTS:=NULL, @prevUser:=NULL) vars order by userid, ping ) sq group by userid, groupnum

更多推荐

MySQL查询按日期范围对结果分组?

本文发布于:2023-10-28 23:13:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538043.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按日   MySQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!