[英]MySQL: count with group by and max limit
我需要計算標記工作量,計算每個標記器添加的標記數量,每個文章的最大標記= 5個標記。
例如:
表結構article_tags
id user_id article_id tag_id
1 1 1 1
2 1 1 2
3 1 2 1
4 2 3 1
5 2 3 2
是否有限制使用Group by或類似的東西? 謝謝,
更新:
我需要返回添加到文章中的標簽數量,單個文章最多5個(所以如果有人為30篇文章添加了30個標簽= 30
這是你想要的嗎?
select user_id, least(count(*), 5)
from article_tags
group by user_id;
編輯:
我想你想要兩個級別的聚合:
select article_id, sum(cnt) as restricted_tag_count
from (select user_id, article_id, least(count(*), 5) as cnt
from article_tags
group by user_id, article_id
) ua
group by article_id;
SELECT USER_ID,ARTICAL_ID,if(count(*)>5,5,count(*)) as tags
from article_tags group by USER_ID,ARTICAL_ID;
你可以嘗試這樣的事情: -
SELECT user_id, CASE WHEN COUNT(tag_id) <= 5 THEN COUNT(tag_id)
ELSE 5 END AS TOTAL_TAGS
FROM YOUR_TABLE
GROUP BY user_id
希望這可以幫助。
基於'Gordon Linoff'的解決方案
SQL查詢:
select t.user_id,sum(t.total_tags) total
from
(
select user_id, least(count(*), 5) total_tags
from article_tags
group by user_id,article_id
) t
group by t.user_id
謝謝,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.