Anda dapat menggunakan age()
. Jika nilainya selalu kurang dari 12 bulan, maka salah satu caranya adalah:
SELECT iv.product_name,
extract(month form age('2020-12-20'::date, MAX(iv.inventory_date::date))) AS months_in_inventory
FROM inventory iv
GROUP BY 1
ORDER BY 1;
Perhitungan yang lebih akurat memperhitungkan tahun:
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_inventory
FROM inventory iv
GROUP BY 1
ORDER BY 1;
Di sini adalah db<>biola.