我想从两个select语句中获得一个组合输出。
首先选择返回某个索引的对象。 第二个选择返回最近的对象。
declare @h geometry select @h = Geom from obj where ObjectIndex = 15054
select ObjectIndex, Geom.STDistance(@h) from obj where ObjectIndex = 15054
union all
select top( 1) ObjectIndex, Geom.STDistance(@h) from obj WITH(index(idx_Spatial)) where Geom.STDistance(@h) < 0.0004
and ObjectLayerName = 'Up_Layer' order by Geom.STDistance(@h)
不幸的是,第二个语句返回了错误的对象。我期望最近的对象,但它返回第二个最接近的实例。 但是,当我只执行第二个select语句时,它返回正确的对象。
select top( 1) ObjectIndex, Geom.STDistance(@h) from obj WITH(index(idx_Spatial)) where Geom.STDistance(@h) < 0.0004
and ObjectLayerName = 'Up_Layer' order by Geom.STDistance(@h)
感谢您的帮助。
答案 0 :(得分:1)
Order by
将在UNION
之后应用,尝试类似这样的内容
DECLARE @h GEOMETRY
SELECT @h = Geom
FROM obj
WHERE ObjectIndex = 15054
SELECT ObjectIndex,
Geom.Stdistance(@h) dist
FROM obj
WHERE ObjectIndex = 15054
UNION ALL
SELECT ObjectIndex,
dist
FROM (SELECT TOP( 1) ObjectIndex,
Geom.Stdistance(@h) AS dist
FROM obj WITH(INDEX(idx_Spatial))
WHERE Geom.Stdistance(@h) < 0.0004
AND ObjectLayerName = 'Up_Layer'
ORDER BY Geom.Stdistance(@h)) a
ORDER BY dist