我有一个SQL查询工作正常,但我觉得必须有一个更有效的方式来编写它。通过连接包含坐标的两个表A和B,我将比较每个坐标之间的距离(以米为单位)。然后我对表B中坐标的坐标数量进行求和/计数,这些坐标在表A中的坐标设定距离内并输出结果:
select a.name,
sum(case when ST_GeodesicLengthWGS84(ST_SetSRID(ST_LineString(a.lat, a.lon, b.lat, b.lon),4326)) < 10.0 then 1 else 0 end) 10mCount,
sum(case when ST_GeodesicLengthWGS84(ST_SetSRID(ST_LineString(a.lat, a.lon, b.lat, b.lon),4326)) < 50.0 then 1 else 0 end) 50mCount,
sum(case when ST_GeodesicLengthWGS84(ST_SetSRID(ST_LineString(a.lat, a.lon, b.lat, b.lon),4326)) < 1000.0 then 1 else 0 end) 1000mCount
FROM a JOIN
b
GROUP BY a.name
ORDER by 1000mCount desc
LIMIT 10;
我觉得必须有一种方法可以调用ST_GeodesicLengthWGS84(ST_SetSRID(ST_LineString(a.lat, a.lon, b.lat, b.lon), 4326))
一次,得到结果然后增加每个10米,50米和1000米的数量。
有什么想法吗? 感谢。
答案 0 :(得分:1)
尝试prequerying,但您的数据仍然需要结果通过每条记录。
select
PreQuery.name,
sum(case when PreQuery.Geode < 10.0 then 1 else 0 end) 10mCount,
sum(case when PreQuery.Geode < 50.0 then 1 else 0 end) 50mCount,
sum(case when PreQuery.Geode < 1000.0 then 1 else 0 end) 1000mCount
from
( select
a.name,
ST_GeodesicLengthWGS84( ST_SetSRID( ST_LineString(a.lat, a.lon, b.lat, b.lon),4326)) as Geode
from
a join b
(YOU ARE MISSING the JOIN 'ON' clause... how related) ) PreQuery
GROUP BY
PreQuery.name
ORDER by
1000mCount desc
LIMIT 10;