SQL,如何提取条目的最大出现次数

时间:2014-10-16 20:21:41

标签: sql

SELECT a.name,a.birth_year,COUNT(a.name)
FROM HUMAN a
WHERE EXISTS(SELECT b.citizenship
                    FROM  NATIONALITY b
                    WHERE b.citizenship='Indian')
GROUP BY a.name,a.birth_year;

我想提取在HUMAN表中具有最大出现次数的名称,并且该人的公民身份是印度人。我试过做MAX(COUNT(a.name)),但它没有用。有什么想法怎么做?

3 个答案:

答案 0 :(得分:1)

也许这就是你想要的:

select h.name
from human h join
     citizenship c
     on h.name = b.name
where c.citizenship = 'Indian'
group by h.name
order by count(*) desc
fetch first 1 rows only;

fetch first 1 rows only是ANSI标准,但并非所有数据库都支持它。您的数据库可能会使用limittop或其他内容。

答案 1 :(得分:0)

SELECT a.name,a.birth_year,COUNT(a.name) as c
FROM HUMAN a
WHERE EXISTS(SELECT b.citizenship
                FROM  NATIONALITY b
                WHERE b.citizenship='Indian')
GROUP BY a.name,a.birth_year
ORDER by c DESC
LIMIT 0, 1;

答案 2 :(得分:0)

是的,使用嵌套的选择查询可以很容易。

Select max(count1),name1 from (
SELECT a.name name1,COUNT(a.name)     count1 FROM HUMAN a WHERE EXISTS(SELECT  b.citizenship FROM NATIONALITY b WHERE b.citizenship='Indian') GROUP BY a.name)