Du kan bruge age()
. Hvis værdien altid er mindre end 12 måneder, så er en metode:
SELECT iv.product_name, extract(month form age('2020-12-20'::date, MAX(iv.inventory_date::date))) AS months_in_inventoryFROM inventory ivGROUP BY 1ORDER BY 1;
En mere nøjagtig beregning tager højde for året:
SELECT iv.product_name, (extract(year from age('2020-12-20'::date, MAX(iv.inventory_date::date))) * 12 + extract(month from age(' 2020-12-20'::date, MAX(iv.inventory_date::date))) ) AS months_in_inventoryFROM inventory ivGROUP BY 1ORDER BY 1;
Her er en db<>violin.