计算位于边界框内的 points/coordinates

Counting points/coordinates that lie within a bounding box

我有 2 个 table。第一个 table 包含以下列:Start_latitude、start_longitude、end_latitude、end_longitude、总和。 sum 列为空,需要根据秒 table 进行填充。

第二个 table 包含 3 列:point_latitude、point_longitude

Table 1

-------------------------
|45 | 50 | 46 | 51 | null|
----|---------------------
|45 | 54 | 46 | 57 | null|
--------------------------

Table2:

---------------
| 45.5 | 55.2 |
---------------
| 45.8 | 50.6 |
---------------
| 45.2 | 56   |
---------------

table1-row1 中的空值将为 1,而在 row2 中将为 2。它是位于边界框内的点数。

我可以在 python 中通过编写函数来读取数据帧之间的值。如何在 Postgresql 中完成此操作。这是我针对我的情况提出的示例问题陈述。

更新 此版本已在 PostgreSql 9.3 上使用 SQL Fiddle

进行测试
UPDATE table1 a
SET sum = sub.point_count
FROM (SELECT a.start_lat, a.end_lat, a.start_lon, a.end_lon, COUNT(*) as point_count
      FROM table1 a, table2 b
      WHERE b.point_lat BETWEEN start_lat AND a.end_lat
        AND b.point_lon BETWEEN a.start_lon AND a.end_lon
      GROUP BY a.start_lat, a.end_lat, a.start_lon, a.end_lon) as sub
WHERE a.start_lat = sub.start_lat
  AND a.end_lat = sub.end_lat
  AND a.start_lon = sub.start_lon
  AND a.end_lon = sub.end_lon;

原回答

这是我的解决方案,已在 MySQL 上进行了测试,但此代码没有任何具体内容,因此它也应该适用于 PostgreSql

UPDATE table1 a,
  (SELECT a.start_lat, a.end_lat, a.start_lon, a.end_lon, COUNT(*) as count
   FROM table1 a, table2 b
   WHERE b.point_lat BETWEEN start_lat AND a.end_lat
   AND b.point_lon BETWEEN a.start_lon AND a.end_lon
   GROUP BY a.start_lat, a.end_lat, a.start_lon, a.end_lon) as sub
SET sum = count
WHERE a.start_lat = sub.start_lat
  AND a.end_lat = sub.end_lat
  AND a.start_lon = sub.start_lon
  AND a.end_lon = sub.end_lon 

请注意,如果 table1 包含 PK Id 列,则此查询会更短。