我有一张桌子,里面有一些数据和相应的城市,州。我希望看到特定州城市中出现的人数最多。如果有100个丹佛,CO和10个出现的Boulder,CO,我想只看到丹佛,因为这是最大的数字。我尝试了以下内容,但它也列出了所有其他城市:
select state, city, count(city)
from tab12
group by city
order by state, count(city);
感谢任何帮助。谢谢。
答案 0 :(得分:1)
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;
答案 1 :(得分:1)
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;
此查询应适用于具有相同计数的多个城市的州。
答案 2 :(得分:0)
未经测试,脱离我的头脑:
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
)
)
请注意,在平局的情况下,这将返回与最高计数相关的每个城市。