14. 空間聯結練習¶
以下是我們看過的一些功能的提醒。提示:這些提示可以協助進行練習!
sum(expression):聚集以傳回一組記錄的總和
count(expression):聚集以傳回一組記錄的大小
ST_Area(geometry) 傳回多邊形的區域
ST_AsText(geometry) 傳回 WKT
text
ST_Contains(geometry A, geometry B) 倘若幾何圖形 A 包含幾何圖形 B,則傳回 true
ST_Distance(geometry A, geometry B) 傳回幾何圖形 A 和幾何圖形 B 之間的最小距離
ST_DWithin(geometry A, geometry B, radius) 倘若幾何圖形 A 與幾何圖形 B 相隔距離在 radius 的範圍內(含)時,則傳回 true
ST_GeomFromText(text) 傳回
geometry
ST_Intersects(geometry A, geometry B) 倘若幾何圖形 A 与幾何圖形 B 相交,則傳回 true
ST_Length(linestring) 傳回線字串的長度
ST_Touches(geometry A, geometry B) 倘若幾何圖形 A 的邊界與幾何圖形 B 相切,則傳回 true
ST_Within(geometry A, geometry B) 倘若幾何圖形 A 座落在幾何圖形 B 內,則傳回 true
請也記住我們可以使用的表格
nyc_census_blocks
name, popn_total, boroname, geom
nyc_streets
name, type, geom
nyc_subway_stations
name, routes, geom
nyc_neighborhoods
name, boroname, geom
14.1. 練習¶
‘小義大利’附近的捷運站是什麼?路線是哪一線?
SELECT s.name, s.routes FROM nyc_subway_stations AS s JOIN nyc_neighborhoods AS n ON ST_Contains(n.geom, s.geom) WHERE n.name = 'Little Italy';
name | routes -----------+-------- Spring St | 6
6 號列車經過哪些社區?(提示:
nyc_subway_stations
表格中的routes
欄位包含 ‘B,D,6,V’ 和 ‘C,6’ 等值)SELECT DISTINCT n.name, n.boroname FROM nyc_subway_stations AS s JOIN nyc_neighborhoods AS n ON ST_Contains(n.geom, s.geom) WHERE strpos(s.routes,'6') > 0;
name | boroname --------------------+----------- Midtown | Manhattan Hunts Point | The Bronx Gramercy | Manhattan Little Italy | Manhattan Financial District | Manhattan South Bronx | The Bronx Yorkville | Manhattan Murray Hill | Manhattan Mott Haven | The Bronx Upper East Side | Manhattan Chinatown | Manhattan East Harlem | Manhattan Greenwich Village | Manhattan Parkchester | The Bronx Soundview | The Bronx
備註
我們使用
DISTINCT
關鍵字,以移除結果集中重複的值(即同個社區中有多個捷運站)。911 事件後,‘砲台公園’ 社區好幾天都管制出入。有多少人必須撤離?
SELECT Sum(popn_total) FROM nyc_neighborhoods AS n JOIN nyc_census_blocks AS c ON ST_Intersects(n.geom, c.geom) WHERE n.name = 'Battery Park';
17153
哪個社區的人口密度(每平方公里人口數)最高?
SELECT n.name, Sum(c.popn_total) / (ST_Area(n.geom) / 1000000.0) AS popn_per_sqkm FROM nyc_census_blocks AS c JOIN nyc_neighborhoods AS n ON ST_Intersects(c.geom, n.geom) GROUP BY n.name, n.geom ORDER BY popn_per_sqkm DESC LIMIT 2;
name | popn_per_sqkm -------------------+------------------ North Sutton Area | 68435.13283772678 East Village | 50404.48341332535