MySQL SELECT most frequent by group

前端 未结 5 1334
盖世英雄少女心
盖世英雄少女心 2020-12-01 22:08

How do I get the most frequently occurring category for each tag in MySQL? Ideally, I would want to simulate an aggregate function that would calculate the mode of a column.

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 22:29

    (Edit: forgot DESC in ORDER BYs)

    Easy to do with a LIMIT in the subquery. Does MySQL still have the no-LIMIT-in-subqueries restriction? Below example is using PostgreSQL.

    => select tag, (select category from stuff z where z.tag = s.tag group by tag, category order by count(*) DESC limit 1) AS category, (select count(*) from stuff z where z.tag = s.tag group by tag, category order by count(*) DESC limit 1) AS num_items from stuff s group by tag;
        tag     | category | num_items 
    ------------+----------+-----------
     ba         |        8 |         1
     automotive |        8 |         1
     bananatree |        8 |         4
     bath       |        9 |         1
     bamboo     |        8 |         9
    (5 rows)
    

    Third column is only necessary if you need the count.

提交回复
热议问题