简体   繁体   English

MySQL中每组SQL的前N个问题

[英]Top N per Group Sql problem in mysql

Please I am having a problem querying for the Top N per category from a data set resembling the one shown below. 请问我在从类似于以下所示的数据集中查询每个类别的前N名时遇到问题。 I have see various thread on this but I am having problem adapting their query to my specific problem. 我在此看到各种线程,但是在将其查询调整为我的特定问题时遇到问题。

+----+---------------------------------+-------+
| ID | Prod                            |Cat Id |
+----+---------------------------------+-------+
|  1 |  kntrn                          |     1 |
|  2 | kntrn e                         |     1 |
|  3 | e spl                           |     1 |
|  4 | spl php                         |     1 |
|  5 | php cicarredgtal                |     1 |
|  6 | cicarredgtal servecounterstrike |     1 |
|  7 | servecounterstrike com          |     1 |
|  8 |  zlv                            |     2 |
|  9 | zlv enter                       |     2 |
| 10 | spl php                         |     2 |
+----+---------------------------------+-------+

I want to group based on this rule (1) Select Top 3 Prod for each catid. 我要基于此规则分组(1)为每个catid选择Top 3 Prod。

Please do note that top in this sense is the one highest count of prod in all category. 请注意,从这个意义上讲,top是所有类别中最高的产品数。

So for the example above spl php is the highest for catID 1 because it occurs twice across all category. 因此,对于上面的示例,spl php对于catID 1最高,因为它在所有类别中都出现两次。

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 |
+--------+-----------+-----+

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

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