With a MySQL table like:
id | colA | colB
...| 1 | 13
...| 1 | 13
...| 1 | 12
...| 1 | 12
...| 1 | 11
...| 2 | 78
...| 2 | 78
...| 2 | 78
...| 2 | 13
...| 2 | 13
...| 2 | 9
For each value in colA
I want to find the N most frequent values in colB
.
Example result for N=2:
colA | colB
1 | 13
1 | 12
2 | 78
2 | 13
I am able to get all unique combinations of colA
and colB
with their frequencies using:
SELECT colA, colB, COUNT(*) AS freq FROM t GROUP BY colA, colB ORDER BY freq DESC;
Example result:
colA | colB | freq
1 | 13 | 2
1 | 12 | 2
1 | 11 | 1
2 | 78 | 3
2 | 13 | 2
2 | 9 | 1
But I struggle to apply a LIMIT
for each value in colA
instead of for the whole table.
This is basically like How to select most frequent value in a column per each id group?, just for MySQL instead of PostgreSQL.
I am using MariaDB 10.1 at the moment.