sql - How to filter the max value and write to row? -
postgres 9.3.5, postgis 2.1.4.
i have tow tables (polygons
, points
) in database.
i want find out how many points
in each polygon
. there 0 points per polygon or more 200000. little hick following.
my point
table looks following:
x y lan 10 11 en 10 11 fr 10 11 en 10 11 es 10 11 en - #just demonstration/clarification purposes 13 14 fr 13 14 fr 13 14 es - 15 16 ar 15 16 ar 15 16 ps
i not want count number of points per polygon. want know occuring lan
in each polygon. so, assuming each -
indicates points falling new polygon, results following:
polygon
table:
polygon count lan 1 3 en 2 2 fr 3 2 ar
this got far.
select count(*), count.language language, hexagons.gid hexagonswhere hexagonslan hexagons, points_count france st_within(count.geom, hexagons.geom) group language, hexagonswhere order hexagons desc;
it gives me following:
polygon count language 1 3 en 1 1 fr 1 1 es 2 2 fr 2 1 es 3 2 ar 3 1 ps
two things remain unclear.
- how max value?
- how cases treated there chance max values identical?
answer 1.
to common language , count per polygon, use simple distinct on
query:
select distinct on (h.gid) h.gid polygon, count(c.geom) ct, c.language hexagonslan h left join points_count c on st_within(c.geom, h.geom) group h.gid, c.language order h.gid, count(c.geom) desc, c.language; -- language name tiebreaker
but data distribution describe (up 200.000 points per polygon), should substantially faster (hoping make better use of index on c.geom
):
select h.gid polygon, c.ct, c.language hexagonslan h left join lateral ( select c.language, count(*) ct points_count c st_within(c.geom, h.geom) group 1 order 2 desc, 1 -- again, language name tiebreaker limit 1 ) c on true order 1;
left join
lateral ..
on true
preserves polygons not containing points.
in cases there chance max values identical
, alphabetically first language picked in example, way of added order by
item. if want all languages happen share maximum count, have more:
answer 2.
select h.gid polygon, c.ct, c.language hexagonslan h left join lateral ( select c.language, count(*) ct , rank() on (order count(*) desc) rnk points_count c st_within(c.geom, h.geom) group 1 ) c on c.rnk = 1 order 1, 3 -- language additional sort critieria
using window function rank()
here, (not row_number()
!). can count or points and ranking of count in single select
. consider sequence of events:
Comments
Post a Comment