Is there a way to ORDER results in MySQL based on a column A and B and then limit the results to X per values of A, as in ORDER BY A, (B LIMIT X)
?
Assume I have table_A in the following format:
+------+--------+------+
| Col1 | Col2 | Col3 |
+------+--------+------+
| A | 100 | abc |
| A | 200 | acd |
| A | 300 | atd |
| A | 400 | aem |
| A | 500 | ieb |
| B | 150 | aio |
| B | 250 | loe |
| B | 350 | wmd |
| B | 450 | zir |
| B | 550 | oui |
+------+--------+------+
I would like to obtain the X highest values of column 2 associated with each value of column 1. Here is an example of the result if I wanted to have the top 3 for each col1 result:
+------+--------+------+
| Col1 | Col2 | Col3 |
+------+--------+------+
| A | 500 | ieb |
| A | 400 | aem |
| A | 300 | atd |
| B | 550 | oui |
| B | 450 | zir |
| B | 350 | wmd |
+------+--------+------+
How could I achieve such a behaviour without relying on one query per value of the column 1?