计数位于边界框中的点/坐标

时间:2018-10-26 21:58:47

标签: sql postgresql pgadmin

我有2张桌子。第一个表包含以下几列:Start_latitude,start_longitude,end_latitude,end_longitude,sum。 sum列为空,需要根据第二个表进行填充。

第二个表包含3列:point_latitude,point_longitude

表1

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

表2:

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

table1-row1中的空值将为1,而row2中的空值将为2。这是边界框中的点数的计数。

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

1 个答案:

答案 0 :(得分:2)

更新 此版本已使用SQL Fiddle在PostgreSql 9.3上进行了测试

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列,则此查询会短得多。

相关问题