2011-12-12 74 views
2

我有我存儲幾何兩個表。如何通過STWithin將SQL Server幾何數據分組?

CREATE TABLE config.region 
(
    id int identity(1,1) PRIMARY KEY, 
    polygon GEOMETRY NOT NULL 
) 

CREATE TABLE config.location 
(
    id int identity(1,1) PRIMARY KEY, 
    position GEOMETRY 
) 

區表將舉行長方形的多邊形。位置表將只包含點。

我想要做的是選擇所有區域,並計算每個多邊形內實際有多少個點。

我想出了這個查詢,它顯示了多邊形ID,位置ID以及位置是否在多邊形中。

SELECT 
    polygon.id as pid, 
    config.location.id as lid, 
    polygon, 
    polygon.STContains(config.location.position) as within 
FROM 
    config.polygon, config.location 

我該如何修改它以給出計數而不是僅僅列出它們是否在彼此之內?

回答

3

我沒有SQL Server 2008,所以我現在無法測試它。你可以試試這個:

select r.id, count(*) as qty 
from config.region r 
join config.location l on r.polygon.STContains(l.position) = 1 
group by r.id 

的所有多邊形:

select p.*, isnull(t.qty, 0) as points_within_polygon 
from config.region p 
left join (
    select r.id, count(*) as qty 
    from config.region r 
    join config.location l on r.polygon.STContains(l.position) = 1 
    group by r.id 
) t on t.id = p.id 

新增: 以下代碼作爲subqery應該可以正常工作爲好。你可以試試哪個更快。

select r.id, sum(cast(r.polygon.STContains(l.position) as int)) as qty 
from config.region r 
cross join config.location l 
group by r.id 

更新: 鑄造bitint增加。

+0

非常感謝!前兩個查詢很好用!最後給出錯誤'操作數數據類型位對求和算子無效'。 – brianestey

+0

@brianestey,我已經糾正了第二個查詢(現在添加了),現在這應該也作爲子查詢。 –

+0

我得到了最後一個查詢的工作,但需要添加一個組聲明 - 我編輯了包含它的答案。再次感謝您的幫助! – brianestey

相關問題