简体   繁体   English

MySQL-按时间间隔选择时间范围内的值

[英]MySQL - Select values in time range by interval

I'm trying to select values from a MySQL Table in a time range grouped by a given interval. 我试图在一个给定间隔分组的时间范围内从MySQL表中选择值。 My actual code looks like this: 我的实际代码如下所示:

SET @dateformat = '%Y-%m-%d %H:%i:%s';
SET @start = '2014-05-07 17:44:15';
SET @stop = '2014-10-27 15:46:58';
SET @interval = 3600;

SELECT  
    t1.id,
    t1.timestamp,
    REPLACE(AVG(t1.A_1), '.', ',') AS avg_val1 
        FROM eco_547702f977d27 AS t1 WHERE timestamp > @start AND timestamp <= @stop GROUP BY UNIX_TIMESTAMP(timestamp) DIV @interval;

This works but groups the values by full hours (18:00, 19:00, 20:00, ...). 这可以工作,但是可以按小时(18:00、19:00、20:00等)对值进行分组。 I want the results to be grouped depending on @start - like 18:44:15, 19:44:15, 20:44:15, ... 我希望根据@start将结果分组-如18:44:15、19:44:15、20:44:15,...

Thank You! 谢谢!

You use a very simple trick here : 您在这里使用一个非常简单的技巧:

Add 44:15 to the time value and then do the same GROUP BY , you'll get the data in the required groups 将时间值添加44:15,然后执行相同的GROUP BY ,您将获得所需组中的数据

I think the easiest way is just to subtract 44*60 + 15 seconds from the value and use that for the interval arithmetic. 我认为最简单的方法是从值中减去44 * 60 + 15秒,并将其用于间隔算术。 Given how you have expressed it: 鉴于您的表达方式:

SELECT t1.id, t1.timestamp, REPLACE(AVG(t1.A_1), '.', ',') AS avg_val1 
FROM eco_547702f977d27 AS t1
WHERE timestamp > @start AND timestamp <= @stop
GROUP BY (UNIX_TIMESTAMP(timestamp) - (44*60 + 15)) DIV @interval;

I would be inclined to put the time in the SELECT : 我倾向于把时间放在SELECT

SELECT t1.id
       FROM_UNIX_TIMESTAMP((UNIX_TIMESTAMP(timestamp) - (44*60 + 15)) DIV @interval) as timestamp,
       REPLACE(AVG(t1.A_1), '.', ',') AS avg_val1 
FROM eco_547702f977d27 AS t1
WHERE timestamp > @start AND timestamp <= @stop
GROUP BY (UNIX_TIMESTAMP(timestamp) - (44*60 + 15)) DIV @interval;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM