Top N per Group Sql problem in mysql

前端 未结 1 779
一生所求
一生所求 2020-12-12 07:18

Please I am having a problem querying for the Top N per category from a data set resembling the one shown below. I have see various thread on this but I am having problem a

相关标签:
1条回答
  • 2020-12-12 07:56

    This may not be very pretty, but I think it'll work:

    SELECT cat_id, prod, pos FROM (
        SELECT cat_id, pos, prod, if(@last_id = cat_id, @cnt := @cnt + 1, (@cnt := 0 || @last_id := cat_id)) cnt
        FROM (
            SELECT p.cat_id, pseq.cnt pos, pseq.prod
            FROM (
                SELECT prod, count(*) cnt FROM prods GROUP BY prod ORDER BY cnt DESC
            ) pseq
            INNER JOIN prods p ON p.prod = pseq.prod
            ORDER BY cat_id, pseq.cnt DESC
        ) po
    ) plist
    WHERE cnt <= 3;
    
    Based on the above data, this will return:
    +--------+-----------+-----+
    | cat_id | prod      | pos |
    +--------+-----------+-----+
    |      1 | spl php   |   2 |
    |      1 |  kntrn    |   1 |
    |      1 | kntrn e   |   1 |
    |      2 | spl php   |   2 |
    |      2 |  zlv      |   1 |
    |      2 | zlv enter |   1 |
    +--------+-----------+-----+
    
    0 讨论(0)
提交回复
热议问题