PostgreSQL求中值问题

本文介绍如何使用PostgreSQL从设备轨迹数据中抽取起始点和中间点。通过具体实例展示了利用百分位连续函数(percentile_disc)选取特定时间点的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

偶碰同事的一个需求,如下描述:

数据库中怎么从一个设备轨迹中抽取三个点,起始点和中间点(根据时间字段)怎么取?每个设备的轨迹点个数不同。

可以使用PostgreSQL的有续集进行处理,测试过程如下所示:

录入测试数据:

sde=# create table test(deviceid int,createtime timestamp, position st_geometry);
CREATE TABLE
sde=# insert into test values (1,now(),st_point(1,1,4326));
INSERT 0 1
sde=# insert into test values (1,now(),st_point(2,2,4326));
INSERT 0 1
sde=# insert into test values (1,now(),st_point(3,3,4326));
INSERT 0 1
sde=# insert into test values (1,now(),st_point(3,3.5,4326));
INSERT 0 1
sde=# insert into test values (1,now(),st_point(4,3.5,4326));
INSERT 0 1
sde=# insert into test values (2,now(),st_point(5,5.5,4326));
INSERT 0 1
sde=# insert into test values (2,now(),st_point(6,6.5,4326));
INSERT 0 1
sde=# insert into test values (2,now(),st_point(5,5.5,4326));
INSERT 0 1
sde=# insert into test values (2,now(),st_point(8,5.5,4326));
INSERT 0 1
sde=# select deviceid,createtime,st_astext(position) from test;
 deviceid |         createtime         |           st_astext
----------+----------------------------+--------------------------------
        1 | 2019-07-18 10:17:24.183081 | POINT ( 1.00000000 1.00000000)
        1 | 2019-07-18 10:17:24.464877 | POINT ( 2.00000000 2.00000000)
        1 | 2019-07-18 10:17:24.722101 | POINT ( 3.00000000 3.00000000)
        1 | 2019-07-18 10:17:24.932533 | POINT ( 3.00000000 3.50000000)
        1 | 2019-07-18 10:17:25.12458  | POINT ( 4.00000000 3.50000000)
        2 | 2019-07-18 10:17:25.32509  | POINT ( 5.00000000 5.50000000)
        2 | 2019-07-18 10:17:25.516098 | POINT ( 6.00000000 6.50000000)
        2 | 2019-07-18 10:17:25.718722 | POINT ( 5.00000000 5.50000000)
        2 | 2019-07-18 10:17:26.183977 | POINT ( 8.00000000 5.50000000)
(9 行记录)

处理SQL:

with t1 as  (select deviceid,percentile_disc(0) within group (order by createtime) as firsttime,percentile_disc(0.5) within group (order by createtime) as middletime from test group by 1)

select t.deviceid,t.createtime,st_astext(t.position) from test t ,t1 where (t.deviceid=t1.deviceid) and (t.createtime=t1.firsttime or t.createtime=t1.middletime)

 deviceid |         createtime         |           st_astext
----------+----------------------------+--------------------------------
        1 | 2019-07-18 10:17:24.183081 | POINT ( 1.00000000 1.00000000)
        1 | 2019-07-18 10:17:24.722101 | POINT ( 3.00000000 3.00000000)
        2 | 2019-07-18 10:17:25.32509  | POINT ( 5.00000000 5.50000000)
        2 | 2019-07-18 10:17:25.516098 | POINT ( 6.00000000 6.50000000)
(4 行记录)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值