As title says, I want to select one record from each month with the latest date. I have a table like this:
ID field1 field2 created_at
----------------------------------------------
1 40000.0000 70000.0000 2018-01-31
2 80000.0000 90000.0000 2018-02-28
3 10000.0000 30000.0000 2018-03-31
4 12000.0000 32000.0000 2018-04-30
5 212500.0000 312500.0000 2018-05-31
6 324000.0000 424000.0000 2018-06-30
7 122300.0000 222300.0000 2018-07-26
8 357772.2420 307600.9081 2018-07-31
I came up with this query, but it's not working as expected.
SELECT id, field1, field2, MAX(created_at) AS created_at FROM
my_table
GROUP BY YEAR(created_at), MONTH(created_at) ORDER BY created_at ASC
The output I'm getting:
ID field1 field2 created_at
----------------------------------------------
1 40000.0000 70000.0000 2018-01-31
2 80000.0000 90000.0000 2018-02-28
3 10000.0000 30000.0000 2018-03-31
4 12000.0000 32000.0000 2018-04-30
5 212500.0000 312500.0000 2018-05-31
6 324000.0000 424000.0000 2018-06-30
7 122300.0000 222300.0000 2018-07-31 <-- values from ID 7 but date from ID 8
Expected output
ID field1 field2 created_at
----------------------------------------------
1 40000.0000 70000.0000 2018-01-31
2 80000.0000 90000.0000 2018-02-28
3 10000.0000 30000.0000 2018-03-31
4 12000.0000 32000.0000 2018-04-30
5 212500.0000 312500.0000 2018-05-31
6 324000.0000 424000.0000 2018-06-30
8 357772.2420 307600.9081 2018-07-31
How can I select values from the same record as MAX(created_at)
?