如何分别将时间列分为5分钟间隔和最大值/最小值SQL? [英] How to group time column into 5 minute intervals and max/min value respectively SQL?
问题描述
我有一个数据库,该数据库的 Datetime 列包含+/- 30秒的间隔,而 Value 列包含10到100之间的随机数.我的表如下所示:
I have a database with a Datetime column containing intervals of +/- 30 seconds and a Value column containing random numbers between 10 and 100. My table looks like this:
datetime value
----------------------------
2016-05-04 20:47:20 12
2016-05-04 20:47:40 44
2016-05-04 20:48:30 56
2016-05-04 20:48:40 25
2016-05-04 20:49:30 92
2016-05-04 20:49:40 61
2016-05-04 20:50:00 79
2016-05-04 20:51:20 76
2016-05-04 20:51:30 10
2016-05-04 20:51:40 47
2016-05-04 20:52:40 23
2016-05-04 20:54:00 40
2016-05-04 20:54:10 18
2016-05-04 20:54:50 12
2016-05-04 20:56:00 55
我想要以下输出:
datetime max_val min_val
-----------------------------------------
2016-05-04 20:45:00 92 12
2016-05-04 20:50:00 79 10
2016-05-04 20:55:00 55 55
在我什至可以继续获取最大值和最小值之前,我首先必须将 datetime 列 GROUP 间隔5分钟.根据我的研究,我想到了这一点:
Before I can even continue getting the maximum value and the minimum value, I first have to GROUP the datetime column into 5 minute intervals. According to my research I came up with this:
SELECT
time,
value
FROM random_number_minute
GROUP BY
UNIX_TIMESTAMP(time) DIV 300
实际上将 GROUPS 的datetime列间隔为5分钟,如下所示:
Which actually GROUPS the datetime column into 5 minute intervals like this:
datetime
-------------------
2016-05-04 20:47:20
2016-05-04 20:50:00
2016-05-04 20:56:00
这非常接近,因为它需要下一个最接近的日期时间,在这种情况下为20:45:00
,20:50:00
等.我想向下舍入 datetime (日期时间)到最近的5分钟,而与 seconds (秒)无关,例如,分钟数是:
This comes very close as it takes the next closest datetime to, in this case, 20:45:00
, 20:50:00
, etc. I would like to rounddown the datetime to the nearest 5 minutes regardless of the seconds, for instance if the minutes are:
minutes rounddown
--------------------
10 10
11 10
12 10
13 10
14 10
15 15
16 15
17 15
18 15
19 15
20 20
时间可能是 14:59 ,我想向下舍入到 10:00 .经过数小时的研究,我也尝试使用此方法:
The time could be 14:59 and I would like to rounddown to 10:00. I also tried using this after hours of research:
SELECT
time,
time_rounded =
dateadd(mi,(datepart(mi,dateadd(mi,1,time))/5)*5,dateadd(hh,datediff(hh,0,dateadd(mi,1,time)),0))
但是不幸的是,这没有用.我收到此错误:
But sadly this did not work. I get this error:
对本地函数'datediff'的调用中参数计数不正确
我也尝试过:
SELECT
time, CASE
WHEN DATEDIFF(second, DATEADD(second, DATEDIFF(second, 0, time_out) / 300 * 300, 0), time) >= 240
THEN DATEADD(second, (DATEDIFF(second, 0, time) / 300 * 300) + 300, 0)
ELSE DATEADD(second, DATEDIFF(second, 0, time) / 300 * 300, 0)
END
返回相同的错误.
我该怎么做?在对 datetime 进行分组之后,如何获得数据分组的最大值和最小值?
How can I do this? And after the datetime is grouped, how can I get the max and min value of the data grouping?
推荐答案
很抱歉,如果我重复另一个答案.我会删除的.
Sorry if I'm repeating another answer. I'll delete if I am..
SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(datetime)/300)*300) x
, MIN(value) min_value
, MAX(value) max_value
FROM my_table
GROUP
BY x;
这篇关于如何分别将时间列分为5分钟间隔和最大值/最小值SQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!