繁体   English   中英

识别构成SQL sum查询一部分的唯一值

[英]Identifying the unique values that form part of a SQL sum query

我有2个查询想一起使用:

1)一个查询求和另一个距离内的几何点的数量,并仅在计数大于6的点返回结果;

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

我想生成一个查询,该查询针对所有(且仅)第一个查询中求和的记录从表t2返回new_ref (理想情况下,输出将是单行中的列,但此刻我什至无法获得针对多行在单列中列出的记录–因此,这是我的首要目标,我可以将枢轴位留到以后) 。

显然,系统正在识别记录以对其进行计数,因此我认为应该可以询问它们是哪些记录……

将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

是的,可以使用子查询:

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
        )

有关简化示例,请参见此SQL Fiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM