st_difference.sql 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. -- The city engineer needs to know the total area of the city's lot area
  2. -- not covered by buildings. In fact, she wants the sum of the lot area
  3. -- after the building area has been removed.
  4. CREATE TABLE buildingfootprints (building_id integer,
  5. lot_id integer,
  6. footprint ST_Multipolygon);
  7. CREATE TABLE lots (lot_id integer,
  8. lot ST_Multipolygon);
  9. INSERT INTO buildingfootprints VALUES(
  10. 506, 1010,
  11. ST_MPolyFromText('multipolygon (((7.0 45.0,15.0 45.0,15.0 51.0,18.0 51.0,18.0 54.0,8.0 54.0,8.0 51.0,7.0 51.0,7.0 45.0)))',1000)
  12. );
  13. INSERT INTO buildingfootprints VALUES(
  14. 543, 2930,
  15. ST_MPolyFromText('multipolygon (((26.0 55.0,38.0 55.0,38.0 48.0,34.0 48.0,34.0 50.0,26.0 50.0,26.0 55.0)))',1000)
  16. );
  17. INSERT INTO buildingfootprints VALUES(
  18. 1208, 203,
  19. ST_MPolyFromText('multipolygon (((8.0 37.0,12.0 37.0,12.0 33.0,17.0 33.0,17.0 22.0,8.0 22.0,8.0 37.0)))',1000)
  20. );
  21. INSERT INTO buildingfootprints VALUES(
  22. 178, 5192,
  23. ST_MPolyFromText('multipolygon (((26.0 33.0,38.0 33.0,38.0 24.0,33.0 24.0,33.0 27.0,26.0 27.0,26.0 33.0)))',1000)
  24. );
  25. INSERT INTO lots VALUES(
  26. 1010,
  27. ST_MPolyFromText('multipolygon (((2 57,21.5 57,21.5 38,2 38,2 57)))',1000)
  28. );
  29. INSERT INTO lots VALUES(
  30. 2930,
  31. ST_MPolyFromText('multipolygon (((21.5 57,40 57,40 38,21.5 38,21.5 57)))',1000)
  32. );
  33. INSERT INTO lots VALUES(
  34. 5192,
  35. ST_MPolyFromText('multipolygon (((21.5 38,40 38,40 20,21.5 20,21.5 38)))',1000)
  36. );
  37. INSERT INTO lots VALUES(
  38. 203,
  39. ST_MPolyFromText('multipolygon (((2 20,2 38,21.5 38,21.5 20,2 20)))',1000)
  40. );
  41. -- The city engineer equijoins the buildingfootprints and lots
  42. -- table on the lot_id and takes the sum of the area of the difference
  43. -- of the lots less the building footprints.
  44. SELECT SUM(ST_Area(ST_Difference(lot,footprint)::ST_MultiPolygon))
  45. FROM buildingfootprints bf, lots
  46. WHERE bf.lot_id = lots.lot_id;