I see that this question is almost a year old, but maybe the answer will serve another person.
The problem is that MySQL does not have the added FIRST and LAST functions of other engines and that they effectively return a value of the first and last record respectively within a GROUP BY. The MAX and MIN functions return the maximum and minimum values respectively, regardless of the ORDER BY clause.
Now if you want to obtain it is simply the last date of each month (although I do not see much sense) would serve you in the following way:
SELECT DATE_FORMAT(mitabla.d, '%Y%m') Mes, MAX(mitabla.d)MaxFechaHora
FROM mitabla
GROUP BY DATE_FORMAT(mitabla.d, '%Y%m')
If you want to work with the last record of each month, the only solution at the SQL level is something like this:
SELECT t.*
FROM mitabla t JOIN
(
/* Esta subconsulta solo te trae la ultima FechaHora de cada mes */
SELECT MAX(mitabla.d)MaxFechaHora
FROM mitabla
GROUP BY DATE_FORMAT(mitabla.d, '%Y%m')
) m ON t.d = m.MaxFechaHora
This only works for you if:
1. In the field d that is DataTime the Date is always saved with the Time, because although if you save only the Date, it will be more or less like this: 2018-09-30 00:00:00 in that case it will return any record of the last day of each month.
2. Do not repeat more than one record in the same second, because the DateTime fields in MySQL do not handle thousandths of a second. If they match more than one record in the same YYYY / MM / DD HH: MM: SS will randomly return any of the repeats.
If you really want to get the last record in a GROUP BY you have to do it by programming:
It's a little more complex, but you can. If it is what you need, if it is what you need, I can explain how to do it.