I have a table of bills where there can be multiple entries for year+month, I need to select only one of each of the year+month pairs. Specifically the pairs with the highest id field, eg the newest entries in the table and crop out older duplicates.
Here is an example query and result, I've added month=1 or 2 to limit size.
SELECT id, year, month, cost_estimate
FROM tblbillforecast
WHERE type = 'E' AND buildingid = 19 AND (month = 1 OR month = 2)
ORDER BY id DESC;
Results:
Desired results:
SELECT * FROM
(SELECT id,year,month,cost_estimate FROM tblbillforecast WHERE type = 'E' and buildingid=19 and (month=1 or month=2) order by id desc) as b
GROUP BY b.month,b.year
The above query works except it is ignoring the order by id desc
that should happen first. I'm not sure what is happening under the hood or if there is a better way to accomplish this but I'm stuck. I've tried more than 10 solutions from other SO similar answers but they don't work for my scenario.