MySQL Get the latest date in each month from a date column.

The following is an example. imagine that each date, separated by commas, is a row in the database

Entrance: - 2010-01-11, 2010-01-18, 2010-01-25, 2010-02-01, 2010-02-08, 2010-02-15, 2010-02-22, 2010-03-01 he must return

Ouput: 2010-01-25, 2010-02-22, 2010-03-01

The result is displayed by getting the last date in the month, the note for March in the database has only one date, so we use this value.

I would appreciate it if anyone could post some pseudo-SQL on how to approach this issue. Notice I am using My-SQL so that these date functions are available.

Greetings

+3
source share
3
SELECT MAX(datecol) FROM sometable
GROUP BY YEAR(datecol), MONTH(datecol);

group by , , .

+8
SELECT max(date_field) FROM date_table GROUP BY YEAR(date_field), MONTH(date_field) ORDER BY date_field ASC;
+2
CREATE FUNCTION [dbo].[GetLastDateOfMonthBetweenTwoDates]

(

    @startdate  DATETIME,
    @enddate    DATETIME

)

RETURNS TABLE
AS

    RETURN (
        with cte
        as
        (
            select cast(cast(year(@startdate) as varchar(4))+'-'+right(100+month(@startdate),2)+'-01' as datetime) ymd
            union all
            select dateadd(m,1,ymd)
            from cte
            where dateadd(m,1,ymd)<=dateadd(m,1,@enddate)
        )
        select dateadd(d,-1,ymd) ymd from cte where dateadd(d,-1,ymd) between @startdate and @enddate
    )
0

Source: https://habr.com/ru/post/1733220/


All Articles