2014-10-08 34 views
0

的一部分,独特的价值观我有2个疑问,我想做出共同努力:识别形成SQL和查询

1)一个查询总结的另一个和收益中提取一定距离内的几何点的数量仅在计数大于6分的情况下结果;

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

我想生成从表返回new_ref单个查询的记录的最小数量) t2适用于所有(仅限)在第一个查询中求和的记录。 (理想情况下,输出将作为单行中的列,但目前我甚至无法将列中列出的记录反对多行 - 所以这是我的第一个目标,我可以将旋转位留在后面) 。

显然,系统识别记录算来,所以我想应该可以问它记录他们...

添加的总和声明第二查询勾销结果。我是否应该将其作为子查询来构造,如果是这样,我该如何做到这一点?

查询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 
+0

欢迎使用堆栈溢出。我已经编辑了你的问题的格式。您可以查看https://stackoverflow.com/editing-help以获得更多关于提高问题可读性的建议。玩的开心! – 2014-10-08 15:57:12

回答

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

+0

感谢您回答Darius - 这个问题可以解决,但由于某种原因,我在查询中并没有处理我的数据。我正在研究它,并在解决问题时再次发布 – somanyquestions 2014-10-14 14:06:32

+0

我收到了关于在** GROUP BY **子句中使用外部引用的错误消息,但是当我将** GROUP BY **更改为引用t3这会运行,而不是t1。但是,当我期望时,我没有收到任何结果。我仍然在努力解决问题所在...... – somanyquestions 2014-10-14 14:22:49

+0

抱歉,您不能剪切/粘贴。其实这个小组是不需要的。另外,嵌套查询的WHERE子句也应该使用t3。 – 2014-10-14 19:10:00