我有一个与这个问题非常相似的查询,我正在创建一个运行总计,直到达到某个值。就我而言,我正在计算县的人口,直到达到所需的人口。
但是,我想按到 lng/lat 的距离来排序搜索,以便我首先添加最近的县。我在下面运行此查询,但没有得到任何结果。当我改为ORDER BY row_id
或任何非空间计算的列时,它会返回结果。我也尝试过使用两个WITH
子句,但我仍然没有得到任何结果。我尝试将其转换distance
为整数,因为它可能没有正确输入,但这没有帮助。
我已经设置了一个测试服务器,您可以在其中使用此端点运行查询
http://sqltestmcr.cartodb.com/api/v2/sql?q=<your query statement here>
这是我正在尝试的查询。以下是有效的变体。您可以通过此链接查看此查询的结果:
http://sqltestmcr.cartodb.com/api/v2/sql?q=SELECT%20*%20FROM%20(%20SELECT%20county,%20the_geom,%20distance,%20row_id_2,%20sum(population)%20over%20(order%20by%20distance%20asc)%20as%20running_total%20FROM%20(%20SELECT%20row_id,%20county,%20population,%20the_geom,%20row_id%20*%202%20AS%20row_id_2,%20ST_Distance(%20ST_Centroid(the_geom),%20ST_GeomFromText('POINT(-72.1235%2042.3521)',%204326)%20)%20AS%20distance%20FROM%20counties_ny_export)%20sq1)%20sq2%20WHERE%20running_total%20%3C=%201400
SELECT
*
FROM (
SELECT
county,
the_geom,
distance,
row_id_2,
sum(population) over (order by distance asc) as running_total
FROM (
SELECT
row_id,
county,
population,
the_geom,
row_id * 2 AS row_id_2,
ST_Distance(
ST_Centroid(the_geom),
ST_GeomFromText('POINT(-72.1235 42.3521)', 4326)
) AS distance
FROM
counties_ny_export
) sq1
) sq2
where running_total <= 1400
以下两个查询适用于我设置ORDER BY row_id
或ORDER BY row_id_2
测试链接的地方row_id
:
http://sqltestmcr.cartodb.com/api/v2/sql?q=SELECT%20*%20FROM%20(%20SELECT%20county,%20the_geom,%20distance,%20row_id_2,%20sum(population)%20over%20(order%20by%20row_id%20asc)%20as%20running_total%20FROM%20(%20SELECT%20row_id,%20county,%20population,%20the_geom,%20row_id%20*%202%20AS%20row_id_2,%20ST_Distance(%20ST_Centroid(the_geom),%20ST_GeomFromText('POINT(-72.1235%2042.3521)',%204326)%20)%20AS%20distance%20FROM%20counties_ny_export)%20sq1)%20sq2%20WHERE%20running_total%20%3C=%201400
SELECT
*
FROM (
SELECT
county,
the_geom,
distance,
row_id_2,
sum(population) over (order by row_id asc) as running_total
FROM (
SELECT
row_id,
county,
population,
the_geom,
row_id * 2 AS row_id_2,
ST_Distance(
ST_Centroid(the_geom),
ST_GeomFromText('POINT(-72.1235 42.3521)', 4326)
) AS distance
FROM
counties_ny_export
) sq1
) sq2
where running_total <= 1400
测试链接row_id_2
:
http://sqltestmcr.cartodb.com/api/v2/sql?q=SELECT%20*%20FROM%20(%20SELECT%20county,%20the_geom,%20distance,%20row_id_2,%20sum(population)%20over%20(order%20by%20row_id_2%20asc)%20as%20running_total%20FROM%20(%20SELECT%20row_id,%20county,%20population,%20the_geom,%20row_id%20*%202%20AS%20row_id_2,%20ST_Distance(%20ST_Centroid(the_geom),%20ST_GeomFromText('POINT(-72.1235%2042.3521)',%204326)%20)%20AS%20distance%20FROM%20counties_ny_export)%20sq1)%20sq2%20WHERE%20running_total%20%3C=%201400