使用window函数处理表中相邻行间类似数据

出租车轨迹数据中,有时候同一辆车会在同一个空间位置发回来很多数据,这时除了时间字段外其他字段内容都相同。为了更好的进行数据清洗,需要处理这样的数据,即将其进行缩减。

数据表定义为:

CREATE TABLE public.taxi_2010
(
tid integer NOT NULL,
isempty smallint,
gpstime timestamp without time zone,
lon real,
lat real
);

比如下面的第1条和第2条就是重复的数据。

 tid  | isempty |   lon   |   lat   |       gpstime       

-------+---------+---------+---------+---------------------

 10037 |       1 | 121.486 | 31.3117 | 2015-04-01 00:31:07

 10037 |       1 | 121.486 | 31.3117 | 2015-04-01 00:31:15

 10037 |       1 | 121.486 | 31.3118 | 2015-04-01 00:31:17

 10037 |       1 | 121.486 | 31.3121 | 2015-04-01 00:31:22

要剔除这样重复的点,可以使用PostgreSQL中的window函数进行处理:

select t1.tid,t1.isempty,t1.lon,t1.lat,t1.gpstime from
(select tid,isempty,lon,lat,gpstime,row_number() over (order by tid,gpstime) as seq1 from taxi_2010 t
order by tid,gpstime) t1
inner join
(select tid,lon,lat,gpstime,row_number() over (order by tid,gpstime) as seq2 from taxi_2010 t
order by tid,gpstime) t2
on t2.seq2=t1.seq1+1 and t1.tid=t2.tid and (not (t1.lat::numeric=t2.lat::numeric and t1.lon::numeric=t2.lon::numeric));

其中,row_number()函数提取当期行号作为唯一id,inner join提取两表中共有的要素,通过行号+1提取邻近行。

参考:

https://blog.csdn.net/u013986802/article/details/74315870


已发布

分类

来自

评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注