如何从sql
中的以下一组或多个记录中找到最小值Date Values
------------------------- ------
2013-07-20 18:05:38.599 257
2013-07-20 18:06:39.264 118
2013-07-20 18:07:39.51 142
2013-07-20 18:08:39.67 138
2013-07-20 18:09:40.279 123
2013-07-20 18:10:40.697 115
2013-07-20 18:11:41.158 124
2013-07-20 18:12:41.327 128
2013-07-20 18:13:41.797 533
2013-07-20 18:14:42.345 129
2013-07-20 18:15:42.694 124
2013-07-20 18:16:43.222 114
2013-07-20 18:17:43.715 119
2013-07-20 18:18:44.162 126
我需要找到时间戳每3分钟的最小值。任何人都可以建议一个查询来工作吗??
答案 0 :(得分:0)
始终指定您的dbms,并在您的问题中提供CREATE TABLE和INSERT语句。
create table test (
date timestamp,
value integer
);
insert into test values
('2013-07-20 18:05:38.599', 257),
('2013-07-20 18:06:39.264', 118),
('2013-07-20 18:07:39.51', 142),
('2013-07-20 18:08:39.67', 138),
('2013-07-20 18:09:40.279', 123),
('2013-07-20 18:10:40.697', 115),
('2013-07-20 18:11:41.158', 124),
('2013-07-20 18:12:41.327', 128),
('2013-07-20 18:13:41.797', 533),
('2013-07-20 18:14:42.345', 129),
('2013-07-20 18:15:42.694', 124),
('2013-07-20 18:16:43.222', 114),
('2013-07-20 18:17:43.715', 119),
('2013-07-20 18:18:44.162', 126);
使用平台的日期/时间功能生成“桶”虚拟表,每个表包含三分钟的间隔。 完全你如何做到这一点因SQL平台而异,因为日期/时间函数在SQL平台之间变化很大。我正在使用PostgreSQL,因此我将在公共表表达式中使用其generate_series()函数。
with buckets as (
select n as start_time, n + interval '3' minute as end_time
from generate_series(timestamp '2013-07-20 18:05:38.599',
timestamp '2013-07-20 18:18:44.162',
'3 minutes') n
)
select min(test.value), start_time, end_time
from test
inner join buckets on test.date >= start_time and test.date < end_time
group by start_time, end_time
order by start_time;
118 2013-07-20 18:05:38.599 2013-07-20 18:08:38.599
115 2013-07-20 18:08:38.599 2013-07-20 18:11:38.599
124 2013-07-20 18:11:38.599 2013-07-20 18:14:38.599
114 2013-07-20 18:14:38.599 2013-07-20 18:17:38.599
119 2013-07-20 18:17:38.599 2013-07-20 18:20:38.599