How to filter max of a YYYYMM field in SQL?

Viewed 18

I have a table where month ID is of YYYYMM format such as 202207 for July 2022. The data type is a number.

I have a scenario where I want to query records from this table only with the most recent month. I'm not able to think of a solution without making the query too complex.

Select a, b
from data
where MonthID = max(MONTHID)

I know the above will not work but something similar perhaps? Any help is much appreciated.

1 Answers

Order by the MonthID column descending, to get the highest value first. Use fetch first with ties to get all the rows with the highest MonthID value.

Select a, b
from data
order by MonthID desc
fetch first 1 row with ties
Related