简体   繁体   English

每30分钟对时间戳进行分组

[英]Grouping timestamp every 30 minutes

I'm trying to group my timestamp every 30 minutes. 我试图每30分钟对我的时间戳进行分组。

I want my result to be like this: 我希望我的结果是这样的:

2016-03-09 00:00:00
2016-03-09 00:30:00
2016-03-09 01:00:00

Instead, my results are this: 相反,我的结果如下:

2016-03-09 00:00:23
2016-03-09 00:35:02
2016-03-09 01:00:03

The query that I'm using is this 我正在使用的查询就是这个

SELECT timestamp
FROM a.tablename
WHERE name = 'example' AND timestamp LIKE '2016-03-09%'
GROUP BY ROUND(((60/30) * HOUR(timestamp) + FLOOR( MINUTE(timestamp) / 30)));

How can I have my desired results? 我怎样才能得到我想要的结果? I've researched other answers on SO and non of the answers helped 我已经研究了关于SO的其他答案,而非答案的帮助

Here's the basic query to group by 30 minutes interval. 这是30分钟间隔分组的基本查询。

SELECT 
FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(timestamp)/(30* 60)) * (30*60)) thirtyHourInterval
FROM tablename
GROUP BY ROUND(UNIX_TIMESTAMP(timestamp)/(30* 60));

Note: ROUND() may lead you towards wrong output. 注意: ROUND()可能会导致输出错误。 Use the following query instead. 请改用以下查询。 Look at the following example: 请看以下示例:

SELECT ROUND(3.7), ROUND(4.2);

Result: 4 4 . 结果: 4 4

Both lies in the same segment. 两者都在同一部分。 The same holds for the above query while rounding the timestamp of different segments might fall in the same segment thus leading towards wrong output 对于上述查询也是如此,而舍入不同段的timestamp可能落在同一段中,从而导致错误的输出

[The following query is Recommended] [推荐以下查询]

SELECT 
FROM_UNIXTIME((UNIX_TIMESTAMP(`timestamp`) DIV (30* 60) ) * (30*60)) thirtyHourInterval
FROM tablename
GROUP BY UNIX_TIMESTAMP(`timestamp`) DIV (30* 60)

SQL FIDDLE DEMO SQL FIDDLE DEMO


Alternatively you can adopt the following query. 或者,您可以采用以下查询。

SELECT 
FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(timestamp)/(30* 60)) * (30*60)) thirtyHourInterval
FROM tablename
GROUP BY ( 4 * HOUR( `timestamp` ) + FLOOR( MINUTE( `timestamp` ) / 30 ));

Relatedpost Relatedpost

One method is to use to_seconds() , truncate the value, and then re-create the datetime value: 一种方法是使用to_seconds() ,截断值,然后重新创建datetime值:

select date_add(0, interval floor(to_seconds(timestamp) / (30 * 60)) second) as timestamp
from a.tablename
where name = 'example' and timestamp >= '2016-03-09' and timestamp < '2016-03-10'
group by date_add(0, interval floor(to_seconds(timestamp) / (30 * 60)) second)
order by 1;

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

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