2010-11-09 116 views
1

我知道足夠的SQL來編寫基本的SELECTUPDATE s。我在努力JOIN s更新結果GROUP BY

我想更新犯罪表中的'縣'字段。我正在使用一個zip_xref表,它會給我縣名。問題在於數百個城市在多個縣,我想更新最普遍的縣的表,所以我的子查詢必須按照大小排列縣。

我寫這個是爲了找到按照每個縣的郵政編碼排列的縣名。

SELECT DISTINCT CountyName AS counties, COUNT(*) AS numZips 
FROM Zip_XRef WHERE (CityName = 'Aurora') AND (StateName = 'Colorado') 
GROUP BY CountyName ORDER BY numZips DESC 

我知道這個更新不起作用,它只是想法。

UPDATE crime_table_08 AS c 
SET county = 
    (SELECT TOP 1 DISTINCT CountyName, COUNT(*) AS numZips 
    FROM Zip_XRef AS z 
    WHERE RTRIM(z.StateName) = RTRIM(c.State) AND RTRIM(z.CityName) = RTRIM(c.city) 
    GROUP BY CountyName ORDER BY numZips DESC 
    ) 

我在想,我需要創建一個臨時表,然後調用它來更新C,我不能完全得到我的頭周圍的邏輯。任何幫助不勝感激。

或者,有沒有人認爲有更好的辦法?

回答

1
UPDATE c 
SET county = t.CountyName 
FROM crime_table_08 AS c 
CROSS APPLY (
    SELECT TOP (1) CountyName 
    FROM (
     SELECT CountyName, COUNT(*) as cnt 
     FROM Zip_XRef AS z 
     WHERE RTRIM(z.StateName) = RTRIM(c.State) AND RTRIM(z.CityName) = RTRIM(c.city) 
     GROUP BY CountyName) 
    ) AS s 
    ORDER BY cnt DESC) as t; 
+0

+1爲獲得一個合理的from子句 – 2010-11-09 23:36:37

+0

對不起,應該提到,我在WIN服務器2003/SQL 2000這將是什麼樣的作爲內加入? – royhink 2010-11-10 18:47:58

+0

不能有相關的內部聯接(即,具有引用'c'別名中的字段的WHERE子句的聯接)。你可以使用子查詢,但它會很快變得非常混亂。稍後我會試着發佈一個解決方案,當我花一分鐘時間看看它。 – 2010-11-10 18:51:10