2011-01-14 63 views
0

我有以下SQL語句 - 它試圖找到所有我們的自行車道,相交郵編: -如何在Sql UPDATE語句中添加TOP 1和PARTITION BY?

UPDATE a 
SET a.ZipCodeId = d.ZipCodeId 
FROM [dbo].[BikePaths] a 
    INNER JOIN [dbo].[BikePathBoundaries] b ON b.ZipCodeId = c.ZipCodeId 
    INNER JOIN [dbo].[ZipCodeBoundaries] c ON b.Boundary.STIntersects(c.Boundary) = 1 

這很好......除非自行車路徑貫穿兩個或更多的郵編(其中一個發生很多)。所以,我想說,Get the zipcode which this bikepath MOSTLY intersects(我有另一個列表中其它地方所有bikpaths到郵編)。

如果這是一個SELECT statemement,它會是這個樣子......

SELECT a.BikePathId, a.BikePathName, c.ZipCodeId, d.ZipCode, 
    c.Boundary.STIntersection(d.Boundary).STArea() AS Area, 
    ROW_NUMBER() OVER (PARTITION BY a.BikePathId ORDER BY c.Boundary.STIntersection(d.Boundary).STArea() DESC) AS RowNumber 
FROM [dbo].[BikePaths] a 
    INNER JOIN [dbo].[BikePathBoundaries] b on a.BikePathId = b.BikePathId 
    INNER JOIN [dbo].[ZipCodeBoundaries] c on b.Boundary.STIntersects(c.Boundary) = 1 
    INNER JOIN [dbo].[ZipCodes] d on c.ZipCodeId = d.ZipCodeId 

,然後我可以再補充一個 TOP 1 WHERE RowNumber = 1,以確保我得到每BikePath一行..這將具有該自行車路徑主要包含在/相交中的郵政編碼。

我知道2nd Sql語句看起來很毛茸茸,加上了Geo-Spatial的東西..但是有人可以幫我將這個語句合併到UPDATE語句中嗎?

回答

3

我不使用地理空間查詢,但不能把你的第二個查詢公用表表達式,並加入它在你的ROW_NUMBER場= 1?

;WITH CTE AS (
SELECT a.BikePathId, c.ZipCodeId, 
    Rnum =ROW_NUMBER() OVER (PARTITION BY a.BikePathId ORDER BY c.Boundary.STIntersection(d.Boundary)) 
FROM  [dbo].[BikePaths] a 
    INNER JOIN [dbo].[BikePathBoundaries] b on a.BikePathId = b.BikePathId 
    INNER JOIN [dbo].[ZipCodeBoundaries] c on b.Boundary.STIntersects(c.Boundary) = 1 
    INNER JOIN [dbo].[ZipCodes] d on c.ZipCodeId = d.ZipCodeId) 
UPDATE a 
SET a.ZipCodeId = cte.ZipCodeId 
FROM [dbo].[BikePaths] a 
    INNER JOIN cte on cte.bikepathid =a.bikepathid and cte.rnum=1; 
+0

CTE的? WTF!不知道那些...... BRB有一些答案我給這個前:) – 2011-01-14 04:39:07