Sql Query:Union All with Top

问题描述 投票:0回答:1

我想从两个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) 

First Query

不幸的是,第二个语句返回错误的对象。我期望最近的对象,但它返回第二个最接近的实例。但是,当我只执行第二个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) 

2. Query without Union

感谢帮助。

sql sql-server-2014 union-all
1个回答
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 
© www.soinside.com 2019 - 2024. All rights reserved.