如何在SQL列中查找最频繁的值并返回该值?

时间:2019-05-20 11:07:52

标签: sql oracle plsql top-n

我正在尝试做这样的事情:

select nume_produs
from incasari 
group by id
having count(nume_produs) =  max(count(nume_produs));  

但这不起作用

3 个答案:

答案 0 :(得分:2)

进行GROUP BY。按计数降序排列。仅获取第一行(最高计数)。

select nume_produs, count(*) as cnt
from incasari 
group by nume_produs
order by cnt desc
fetch first 1 row with ties

答案 1 :(得分:2)

对于列中最常见的值:

select num_produs
from (select nume_produs, count(*) as cnt,
             row_number() over (order by count(*)) as seqnum
      from incasari
      group by nume_produs
     ) i
where seqnum = 1;

如果在重复的情况下需要多个值,请使用rank()而不是row_number()

如果您想要最常见的值每个ID ,则添加partition by

select num_produs
from (select nume_produs, count(*) as cnt,
             row_number() over (partition by id order by count(*)) as seqnum
      from incasari
      group by nume_produs
     ) i
where seqnum = 1;

答案 2 :(得分:-2)

SELECT       `nume_produs`,
             COUNT(`nume_produs`) AS `value_occurrence` 
    FROM     `incasari`
    GROUP BY `nume_produs`
    ORDER BY `value_occurrence` DESC
    LIMIT    1;

如果要查看列的N个最常用的值,请增加1。