I am working on migrating a report from MySQL to Postgres and I am trying to get the latest records per each category group by Year and Month, in MySQL it looks like this:
select Category,
max(DATECOL) AS Date
from Table
group by Category, date_format(DATECOL,'%Y-%m')
order by DATECOL desc;
+----------+------------+
| Category | Date |
+----------+------------+
| A | 2021-05-27 |
+----------+------------+
| B | 2021-05-27 |
+----------+------------+
| A | 2021-04-30 |
+----------+------------+
| B | 2021-04-30 |
+----------+------------+
| A | 2021-03-31 |
+----------+------------+
| B | 2021-03-31 |
+----------+------------+
But When I try the following in Postgres it gives me a "Must include DATECOL in GROUP BY"
error message and when I include DATECOL it just returns every possible dates. Is there a way to get the max records per category in Postgres? . Here is what I had tried in Postgres which returns the "Must include DATECOL in GROUP BY"
error
select Category,
max(DATECOL) AS DATE
from Table
group by Category, concat(EXTRACT(year from DATECOL),'-', EXTRACT(month from DATECOL) )
order by DATECOL desc;