MySQL SELECT most frequent by group

前端 未结 5 1335
盖世英雄少女心
盖世英雄少女心 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:20

    SELECT  tag, category
    FROM    (
            SELECT  @tag <> tag AS _new,
                    @tag := tag AS tag,
                    category, COUNT(*) AS cnt
            FROM    (
                    SELECT  @tag := ''
                    ) vars,
                    stuff
            GROUP BY
                    tag, category
            ORDER BY
                    tag, cnt DESC
            ) q
    WHERE   _new
    

    On your data, this returns the following:

    'automotive',  8
    'ba',          8
    'bamboo',      8
    'bananatree',  8
    'bath',        9
    

    Here's the test script:

    CREATE TABLE stuff (tag VARCHAR(20) NOT NULL, category INT NOT NULL);
    
    INSERT
    INTO    stuff
    VALUES
    ('automotive',8),
    ('ba',8),
    ('bamboo',8),
    ('bamboo',8),
    ('bamboo',8),
    ('bamboo',8),
    ('bamboo',8),
    ('bamboo',10),
    ('bamboo',8),
    ('bamboo',9),
    ('bamboo',8),
    ('bamboo',10),
    ('bamboo',8),
    ('bamboo',9),
    ('bamboo',8),
    ('bananatree',8),
    ('bananatree',8),
    ('bananatree',8),
    ('bananatree',8),
    ('bath',9);
    

提交回复
热议问题