简体   繁体   English

MySQL:提取元素的最频繁值

[英]MySQL: extract the most frequent value for an element

I have a DB table with a set of Texts and, for each of them, five (5) emotions. 我有一个带有一组文本的DB表,每个文本都有五(5)种情绪。 What I need to do is to get the most frequent emotion for each group of rows, only if that emotion appears at least three times. 我需要做的是让每组行中出现最频繁的情绪,前提是该情绪至少出现3次。 Otherwise, I do not want to show the aggregated row in the result set. 否则,我不想在结果集中显示汇总的行。 For instance I have: 例如,我有:

text     | emotion
nice day | happyness
nice day | happyness
nice day | neutral
nice day | neutral
nice day | happyness
hello    | sadness
hello    | sadness
hello    | surprise
hello    | surprise
hello    | neutral

And the output should be: nice day | 输出应为:美好的一天| happyness 快乐
In that case, the text "Hello" is not displayed, since there are no emotions that occur at least 3 times. 在这种情况下,由于不会出现至少3次情绪,因此不会显示文本“ Hello”。

I tried many solutions but I cannot find a working one... 我尝试了许多解决方案,但找不到可行的解决方案...

This is a bit tricky: 这有点棘手:

select text, emoticon
from t
group by text, emoticon
having count(*) >= 3 and
       count(*) = (select count(*)
                   from t t2
                   where t2.text = t.text
                   group by t2.emoticon
                   order by count(*) desc
                   limit 1
                  );

let's say your table name is emotions so the code will be 假设您的表格名称是情感,因此代码将是

select text,emotion
from emotions
group by text,emotion
having count(emotion)>2

The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns GROUP BY语句通常与聚合函数(COUNT,MAX,MIN,SUM,AVG)一起使用,以将结果集按一列或多列分组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM