且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PostgreSQL中两个日期之间的差异

更新时间:2022-04-14 09:11:41

尝试:

date_part('year',age(coalesce(d1,current_date), d2))::int;

age(d1,d2)函数返回以下格式的两个日期之间的年,月和日的数量:

age(d1,d2) function returns the number of years, months, and days between two dates in following format:

xxx year(s) xxx mon(s) xxx day(s).

从此输出使用 date_part()选择唯一的年份差异。并且也不需要放置if语句来处理 NULL ,因为我添加了 coalesece ,该返回第一个 NON Null 值,因此,如果 d1 NULL ,则返回 cuurent_date

from this output using date_part() to pick the only the year difference. and also no need to put if statement to handle NULL as I have added coalesece which returns first NON Null value, So if d1 is NULL it return cuurent_date

功能结构:

CREATE OR REPLACE FUNCTION diff(d1 date,d2 date) RETURNS int AS $$
BEGIN

 RETURN date_part('year',age(coalesce(d1,current_date), d2))::int;
END
$$ language plpgsql;

函数调用:

select * from diff(null,'2010-04-01');
select * from diff('2012-10-01','2010-04-01');