标识构成SQL求和查询一部分的唯一值

时间:2014-10-08 15:48:08

标签: sql sql-server spatial-query

我有两个想要一起工作的查询:

1)一个查询将几何点的数量与另一个点的某个距离相加,并仅在计数值大于6点时返回结果;

2)一个查询返回该距离内所有点的唯一ID(没有计数,因此也没有最小记录数)

我想生成一个单独的查询,该查询从表new_ref返回t2所有(且仅限)在第一个查询中求和的记录。 (理想情况下,输出将作为单行中的列,但目前我甚至无法将单个列中列出的记录与多行相关联 - 所以这是我的第一个目标,我可以将旋转位留到以后) 。

显然,系统正在识别记录以计算它们,所以我认为应该可以询问它们是哪些记录......

将sum语句添加到第二个查询会使结果无效。我应该将其构建为子查询吗?如果是,我该怎么做?

查询1是:

DECLARE @radius as float = 50   
SELECT 
  t1.new_ref,
  t1.hatrisref,
  SUM
  (CASE WHEN t1.geolocation.STDistance(t2.Geolocation) <= @radius
   THEN 1 Else 0
   End) Group size'    
FROM table1 as t1,
     table1 as t2  
WHERE
  [t1].[new_ref] != [t2].[new_ref] 
GROUP BY
  [t1].[new_ref],
  [t1].[hatrisref]
HAVING
  SUM(CASE WHEN
    t1.geolocation.STDistance(t2.Geolocation) <= @radius
    THEN 1 Else 0
  End) >5
ORDER BY
  [t1].[new_ref],
  [t1].[hatrisref]

查询2是:

DECLARE @radius as float = 50
SELECT 
  t1.hatrisref,
  t1.new_ref,
  t2.new_ref
FROM table1 as t1,
     table1 as t2  
WHERE
  [t1].[new_ref] != [t2].[new_ref] 
  and 
  t1.geolocation.STDistance(t2.Geolocation) <= @radius
GROUP BY
  [t1].[new_ref],
  [t1].[hatrisref],
  t2.new_ref
ORDER BY
  [t1].[hatrisref],
  [t1].[new_ref],
  t2.new_ref

1 个答案:

答案 0 :(得分:0)

是的,子查询可以起作用:

SELECT ...
FROM table1 as t1,  table1 as t2  
WHERE t1.new_ref != t2.new_ref 
  and t1.geolocation.STDistance(t2.Geolocation) <= @radius
and 5 < (select count(*)
         from table1 as t3
         WHERE t1.new_ref != t3.new_ref 
         and t1.geolocation.STDistance(t3.Geolocation) <= @radius
        )

有关简化示例,请参阅this SQL Fiddle