get the last record of each month

0

hi I have a question I am trying to filter a query in the following way with mysql:

SELECT a, b, d
FROM 
    mitabla
GROUP BY d;

Where d is a column type: datetime , the idea is to bring the last record of each month, if possible. but it brings me everything.

    
asked by Francisco Núñez 29.01.2018 в 20:52
source

3 answers

0

Try creating a temporary table nested in the same query, grouped by month and then year, sort by date. Then select only the maximum id (assuming it is incremental autonumeric). The table will return the id of the last record of each month and year. You use that id to select the rest of the columns you require from the original table.

 select a, b, d  from mitabla,(SELECT Max(id), MONTH(d) as mes,YEAR(d) as ano 
    FROM 
        mitabla
    GROUP BY mes,ano order by d desc) as fechas 

    Where mitabla.id=fechas.id
    
answered by 29.01.2018 в 22:11
0

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.

    
answered by 01.10.2018 в 13:08
-2
SELECT a, b, d 
FROM mitabla
GROUP BY d
order by desc d
limit 1;

More or less around there Greetings.

    
answered by 29.01.2018 в 20:59