使用GROUP BY的结果进行更新

时间:2010-11-09 23:23:01

标签: sql sql-server tsql

我知道足够的SQL来编写基本的SELECTUPDATE。我正在努力与JOIN s

我想更新犯罪表中的“县”字段。我正在使用一个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 个答案:

答案 0 :(得分: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;