我想根据postgres sql中给定的公差对时间间隔进行分组

时间:2020-03-28 15:32:59

标签: sql postgresql

create table sample(id integer, name varchar(100), timeint time);

insert into sample values(1, 'aaa', '00:00:01');
insert into sample values(1, 'aaa', '00:00:01');
insert into sample values(1, 'aaa', '00:00:02');
insert into sample values(1, 'aaa', '00:00:03');
insert into sample values(1, 'aaa', '00:00:04');
insert into sample values(2, 'bbb', '00:00:01');
insert into sample values(2,'bbb', '00:00:02');
insert into sample values(2, 'bbb', '00:00:03');

select id,name,timeint,count(timeint) from sample
group by id,name,timeint;

------输出将类似于----

1   aaa 00:00:01    2
1   aaa 00:00:02    1
1   aaa 00:00:03    1
1   aaa 00:00:04    1
2   bbb 00:00:01    1
2   bbb 00:00:02    1
2   bbb 00:00:03    1

因此,上述输出应以这样的方式重新组合:对于相同的id和name,具有1秒容差的timeint应该被视为相同

______预期输出_________________

1   aaa 00:00:01    3
1   aaa 00:00:03    2
2   bbb 00:00:01    2
2   bbb 00:00:03    1 

2 个答案:

答案 0 :(得分:0)

解决问题的一般方法需要递归CTE。如果所有时间都精确到一秒,而您只想要两秒钟,那么可能有解决方法。

但是,此解决方案使用递归CTE:

Swal.fire('Any fool can use a computer')

Here是db <>小提琴。

答案 1 :(得分:0)

对于此示例数据,您可以应用逻辑,即所有具有偶数秒数的MANUFACTURER_ID = 0x0118;应与前一个timeint(-1秒)分组:

timeint

请参见FlutterBeacon
结果:

select 
  id, 
  name, 
  timeint - interval '1 seconds' * (mod(extract(second from timeint)::int, 2) = 0)::int  time_int, 
  count(*) counter
from sample
group by id, name, time_int
order by id, name, time_int