mysqlsqlsql-servert-sqldenodo

Max date for every month


In the following you can see an example of my table:

test_id     test_date     test_date_from    cash_per_step
1           2020-01-01    2019-12-30        30
1           2020-01-21    2019-12-30        40
1           2020-02-28    2019-12-30        30
2           2020-01-01    2019-12-30        30
2           2020-01-21    2019-12-30        40
2           2020-02-28    2019-12-30        30

As you can see, there is no unique ID (unfortunately I cannot change it either). I want to create a view that ONLY contains the rows that contain the MAX (test_date) for each MONTH for every test_id!

So like this:

test_id     test_date     test_date_from    cash_per_step
1           2020-01-21    2019-12-30        40
1           2020-02-28    2019-12-30        30
2           2020-01-21    2019-12-30        40
2           2020-02-28    2019-12-30        30

The data is only test data, please excuse that it is double. I am only interested in the functionality of the query.


Solution

  • This should work in both MySQL (8.0+) and SQL Server.

    SELECT DISTINCT
        test_id,
        FIRST_VALUE(test_date) OVER (PARTITION BY test_id,MONTH(test_date), YEAR(test_date) 
                                     ORDER BY test_date desc ) as test_date,
        FIRST_VALUE(test_date_from) OVER (PARTITION BY test_id,MONTH(test_date), YEAR(test_date) 
                                          ORDER BY test_date desc ) as test_date_from,
        FIRST_VALUE(cash_per_step) OVER (PARTITION BY test_id,MONTH(test_date), YEAR(test_date) 
                                         ORDER BY test_date desc ) as cash_per_step
    FROM YourTable