你好这样写
SELECT name, COUNT(name) AS value_occurrence
FROM table
GROUP BY name
ORDER BY value_occurrence DESC;
我得到这张表:
name occurrence
---- ---------
a 6
b 5
c 3
但是我想要大多数人的名字发生了一个a。我应该为此目的写什么?(我用的是sql)
答案 0 :(得分:1)
在Oracle中,这将使您的姓名频繁出现或者比其他所有名称更频繁地出现:
SELECT name, value_occurrence
FROM (
SELECT name, COUNT(name) AS value_occurrence
FROM table
GROUP BY name
ORDER BY value_occurrence DESC )
WHERE rownum = 1;
换句话说,如果有两个名称的出现次数最多,则上述查询将为您提供其中一个(随机)。如果您不喜欢随机方面,可以根据需要将ORDER BY value_occurrence DESC
更改为ORDER BY value_occurrence DESC, name
。
如果在平局的情况下,你想看到所有与1st相关的名字,你可以这样做:
SELECT name, value_occurrence
FROM (
SELECT name, count(*), dense_rank() over ( partition by null order by COUNT(name) desc) AS value_occurrence_pos
FROM table
GROUP BY name
ORDER BY value_occurrence DESC )
WHERE value_occurence_pos = 1;
答案 1 :(得分:-3)
答案1为真,但可能会发生2次错误: