[英]MySQL: extract the most frequent value for an element
我有一個帶有一組文本的DB表,每個文本都有五(5)種情緒。 我需要做的是讓每組行中出現最頻繁的情緒,前提是該情緒至少出現3次。 否則,我不想在結果集中顯示匯總的行。 例如,我有:
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
輸出應為:美好的一天| 快樂
在這種情況下,由於不會出現至少3次情緒,因此不會顯示文本“ Hello”。
我嘗試了許多解決方案,但找不到可行的解決方案...
這有點棘手:
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
);
假設您的表格名稱是情感,因此代碼將是
select text,emotion
from emotions
group by text,emotion
having count(emotion)>2
GROUP BY語句通常與聚合函數(COUNT,MAX,MIN,SUM,AVG)一起使用,以將結果集按一列或多列分組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.