简体   繁体   English

MySQL:使用group by和max limit计数

[英]MySQL: count with group by and max limit

I need to count taggers efforts, by count how many tags added by each tagger, with maximum tag for each article = 5 tags. 我需要计算标记工作量,计算每个标记器添加的标记数量,每个文章的最大标记= 5个标记。

ex: 例如:

  1. If tagger added 4 tags to one Article count 4. 如果tagger在一个文章计数4中添加了4个标签。
  2. If tagger added 5 tags to one Article count 5. 如果tagger将5个标签添加到一个文章计数5。
  3. If tagger added 6 tags to one Article count 5. 如果tagger在一个文章计数5中添加了6个标签。
  4. If tagger added 10 tags to one Article count 5. 如果tagger将10个标签添加到一个文章计数5。

table structure article_tags 表结构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

Is there advanced use of Group by with limit, or something like this? 是否有限制使用Group by或类似的东西? thx, 谢谢,

update: 更新:

I need to return how many tags added to articles, with max 5 for a single article, (so If someone added 30 tags for 30 articles = 30 我需要返回添加到文章中的标签数量,单个文章最多5个(所以如果有人为30篇文章添加了30个标签= 30

Is this what you want? 这是你想要的吗?

select user_id, least(count(*), 5)
from article_tags
group by user_id;

EDIT: 编辑:

I think you want two levels of aggregation: 我想你想要两个级别的聚合:

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;

You can try something like this:- 你可以尝试这样的事情: -

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

Hope this helps. 希望这可以帮助。

Solution based on 'Gordon Linoff' 基于'Gordon Linoff'的解决方案

SQL query: 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

thx, 谢谢,

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

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