For example, if Column A and Column B have values:
+---+---+
| A | B |
+---+---+
| 2 | 1 |
| 5 | 1 |
| 6 | 1 |
| 1 | 2 |
| 5 | 2 |
| 0 | 2 |
| 2 | 3 |
| 7 | 3 |
| 4 | 3 |
| 5 | 4 |
+---+---+
From each group of B, I want to get the highest number from A. However, I don’t want to include results where the number in B is higher, yet has a smaller A value than the previous one. I know this doesn’t make sense in words, but this is what I want the final result to look like:
+---+---+
| A | B |
+---+---+
| 6 | 1 |
| 7 | 3 |
+---+---+
So far I have something like “select max(a), b from table1 group by b” but this doesn’t omit the ones where B is higher but the max A is smaller. I know that I could just peruse the results of that query in PHP and remove the ones where the A value is smaller than the previous A value, but I want to put it all in the mysql query if possible.
A simpler solution would be to use a variable to store the value of
afrom the previous row and make the comparison on each iteration. This also accounts for the case where you might have gaps in thebcolumn, where numbers aren’t exactly in perfect sequential order: