2014-10-08 75 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