Sql 查询:将所有内容与顶部合并
Sql Query: Union All with Top
我想得到两个 select 语句的组合输出。
首先selectreturns某个索引的对象。
第二个 select returns 最近的对象。
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)
不幸的是,第二个语句returns对象错误。我期待最近的对象,但它 returns 第二个最近的实例。
但是,当我只执行第二个 select 语句时它 returns 正确的对象。
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)
感谢您的帮助。
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
我想得到两个 select 语句的组合输出。
首先selectreturns某个索引的对象。 第二个 select returns 最近的对象。
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)
不幸的是,第二个语句returns对象错误。我期待最近的对象,但它 returns 第二个最近的实例。 但是,当我只执行第二个 select 语句时它 returns 正确的对象。
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)
感谢您的帮助。
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