使用lag 访问以前的数据行。但首先必须将字符串解析为浮点数:
select *,lon-lon_old as diff_lon, lat-lat_old as diff_lat
#RouteID , count(1)
from (
select *,
lag(lon) over (partition by RouteID order by row) as lon_old,
lag(lat) over (partition by RouteID order by row) as lat_old
from (
select
row_number() over () as row ,RouteID,
cast(split(data,",")[offset(0)] as float64) as lon,
cast(replace(split(data,",")[offset(1)],"]","") as float64) as lat
from(
select RouteID, split(substring(geo,3),"],[") as data from (
SELECT
routeID , json_extract(st_asgeojson(st_makeline(
array_agg(st_geogpoint(locs.lon, locs.lat) order by
locs.date))),'$.coordinates') as geo,
FROM
(select 1 as RouteID, [struct(5 as lon,5 as lat, current_date() as date), struct(1,2,"2020-01-01") ] as locations UNION ALL
select 2 as RouteID, [struct(15 as lon,15 as lat, current_date() as date), struct(1,2,"2020-01-01") ]
)
cross join UNNEST(locations) as locs
#where locs.date between {{start_date}} and {{end_date}}
group by routeID
order by routeID
limit 1000
)where length(geo)-length(replace(geo,"]","")) > 1+4
), unnest(data) data
))
#where lon-lon_old>0.5 or lat-lat_old>0.5
#group by 1
一个更简单的例子是
With dat as (select [struct(-79.88523 as A, 30.2566 as B), struct(-65.5523,25.256)] as data )
select *,value.A-old.A as diff_A
from (
select *, lag(value) over (order by row) as old
from (
select row_number() over () as row, value
from dat, unnest (dat.data) as value
)
)