2011-01-14 34 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