我有一个表,其中包含一些数据和相应的城市、州。我想查看一个城市在特定州的出现次数最多。假设如果有 100 次 Denver,CO 和 10 次 Boulder,CO 出现,我只想看到 Denver,因为这是最大的数字。我尝试了以下方法,但它也列出了所有其他城市:
select state, city, count(city)
from tab12
group by city
order by state, count(city);
任何帮助表示赞赏。谢谢。
我有一个表,其中包含一些数据和相应的城市、州。我想查看一个城市在特定州的出现次数最多。假设如果有 100 次 Denver,CO 和 10 次 Boulder,CO 出现,我只想看到 Denver,因为这是最大的数字。我尝试了以下方法,但它也列出了所有其他城市:
select state, city, count(city)
from tab12
group by city
order by state, count(city);
任何帮助表示赞赏。谢谢。
SELECT A.* FROM
(
SELECT city,state,COUNT(1) citycount
FROM tab12 GROUP BY state,city
) A INNER JOIN
(
SELECT state,MAX(citycount) citycount FROM
(SELECT state,city,COUNT(1) citycount
FROM tab12 GROUP BY state,city) C
) B
USING (state,citycount)
ORDER BY A.state,A.city;
此查询应该适用于拥有多个城市且数量相同的州。
SELECT state, city, max(cnt)
FROM
(select state, city, count(city) as cnt
from tab12 group by city order by state, count(city))
order by state
如果您还想涵盖可能具有相同频率的城市的情况:
SELECT state, city, count(*) cnt
FROM cities GROUP BY state,city
HAVING cnt = (SELECT max(cnt)
FROM
(SELECT count(*) cnt FROM cities group by state,city) as tbl)
ORDER BY state;
未经测试,在我脑海中浮现:
select state as thestate, city as thecity, count(*) as thecount
from tab12
group by state, city
having thecount = (
select max(subcnt)
from(
select count(*) as subcnt
from tab12 sub
where sub.state = thestate
group by sub.city
)
)
请注意,在平局的情况下,这将返回与最高计数并列的每个城市。