【實例】POSTGRE SQL如何用age函數(shù)實現(xiàn)兩個日期之間的差值計算用法及代碼示例
工作中遇到需要計算兩個日期之間的月份差值、天數(shù)差值,百度到的眾多內(nèi)容自己通過實踐整理后,將最終的計算結(jié)果分享給大家
例:
用到的函數(shù):age(end_date,start_date)
age函數(shù)常用來計算年齡,計算兩個日期之間的差值
這里current_date是當(dāng)前系統(tǒng)時間,為:
select current_date
系統(tǒng)返回賬期為:
2023-10-20
既當(dāng)前日期為:2023-10-20
第二個參數(shù)賬期后::timestamp是將該值強制轉(zhuǎn)換為timestamp類型,才可用做計算:
select age(current_date , '2022-11-04'::timestamp)
返回結(jié)果為:
{"hours":0,"seconds":0.0,"months":11,"minutes":0,"days":16,"type":"interval","value":"0 years 11 mons 16 days 0 hours 0 mins 0.00 secs","years":0}
這里會將年份之間的差值、月份之間、天數(shù)之間對應(yīng)差值都對應(yīng)計算出來
當(dāng)我們將其轉(zhuǎn)換為varchar格式后:
select cast(age(current_date , '2022-11-04'::timestamp) as varchar)
返回結(jié)果會變?yōu)椋?br> 會直接返回有參數(shù)的值,既賬期差值:
11 mons 16 days
看到這里你是否已經(jīng)明白該如何計算兩個賬期之間的差值了呢?如果只想要相差的年份、月份、天數(shù)中的一種的話,可以加入extract函數(shù),單獨提取出年份差值,月份差值,或者天數(shù)差值來
例:
select
extract(year from age(current_date , '2022-03-04'::timestamp)) as interval_years -- 間隔的年數(shù)
,extract(month from age(current_date , '2022-03-04'::timestamp)) as interval_month -- 間隔的月數(shù)
,extract(day from age(current_date , '2022-03-04'::timestamp)) as interval_day -- 間隔的天數(shù)
返回結(jié)果為:
interval_years 1.0
interval_month 7.0
interval_day 16.0
大家可以自己計算一下,
2023-10-20 到 2022-03-04 的差值 是不是就是差了1年7個月16天?
想全部轉(zhuǎn)換為天數(shù)或者月數(shù)的話,自己再計算一下就好了,這里一個月按30天,一年按365天計算了:
select
interval_years*365+interval_month*30+interval_day as interval_all_days -- 間隔的總天數(shù)計算
,interval_years*12+interval_month as interval_all_months -- 間隔的總天數(shù)計算
from
(
select
extract(year from age(current_date , '2022-03-04'::timestamp)) as interval_years -- 間隔的年數(shù)
,extract(month from age(current_date , '2022-03-04'::timestamp)) as interval_month -- 間隔的月數(shù)
,extract(day from age(current_date , '2022-03-04'::timestamp)) as interval_day -- 間隔的天數(shù)
)a
返回結(jié)果為:文章來源:http://www.zghlxwxcb.cn/news/detail-763315.html
interval_all_days 591.0
interval_all_months 19.0
這兩個日期按天數(shù)計算共差了591天,按月份來看差了19個月,你學(xué)會了嗎?文章來源地址http://www.zghlxwxcb.cn/news/detail-763315.html
到了這里,關(guān)于【實例】POSTGRE SQL如何用age函數(shù)實現(xiàn)兩個日期之間的差值計算用法及代碼示例的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!