Skip to content
Advertisement

Calculate exact month-difference between two dates

DB-Fiddle

Expected result:

I want to calculate the months_in_inventory by calculating the difference between a fixed_date and the inventory_date.

In the example the fixed_date is '2020-12-20' and I am using it my query.

So far I am able to calculate the difference in days:

However, I could not figure out how to change it to a difference in month. Do you have any idea?

NOTE

I know that one way to approach this would be extracting the month from the fixed_date and inventory_date and subtract both numbers. However, this would not give me the correct result because I need it exactly based on the dates.

For example Product_B is only 1 month in inventory because 2020-10-22 is not two months compared to 2020-12-20.

Advertisement

Answer

You can use age(). If the value is always less than 12 months, then one method is:

A more accurate calculation takes the year into account:

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement