Assuming you want a record for each month, then consider the following solution using window function ROW_NUMBER()
:
SELECT id, account, date, amount
FROM
(
SELECT yt.*,
ROW_NUMBER() OVER (PARTITION BY EXTRACT(YEAR FROM date), EXTRACT(MONTH FROM date) ORDER BY date DESC) as rn
FROM yourtable yt
)dt
WHERE rn = 1;
This ROW_NUMBER()
window function feature is generating a row_number, starting at 1, for each row that shares the same month and year, ordering by the date
column descending. The record that gets rn
of 1
is the highest date for that month/year combination.
Using similar logic as I shared in the comment, which is likely slower since two table scans are needed:
SELECT *
FROM yourtable yt
WHERE date =
(
SELECT max(date)
FROM yourtable yt2
WHERE
EXTRACT(MONTH FROM yt.date) = EXTRACT(MONTH FROM yt2.date
AND EXTRACT(YEAR FROM yt.date) = EXTRACT YEAR FROM yt2.date)
)