[英]Difference between two dates in postgresql
Function: 功能:
CREATE FUNCTION diff(d1 date,d2 date) RETURNS int AS $$
BEGIN
IF d1 = NULL THEN
RETURN SELECT extract(year from age(current_date,d2));
ELSE
RETURN SELECT extract(year from age(d1,d2));
END IF;
END
$$ language plpgsql;
My requirement is to find the difference between two dates in years. 我的要求是找出几年中两个日期之间的差。 So, I write the above function.
所以,我写了上面的函数。 Here, if d1 is NULL then it is assigned with current date.
在此,如果d1为NULL,则将其分配为当前日期。 But, it produce error like as shown below.
但是,它会产生如下所示的错误。
ERROR: syntax error at or near "SELECT"
LINE 1: SELECT SELECT extract(year from age(current_date, $1 ))
QUERY: SELECT SELECT extract(year from age(current_date, $1 ))
CONTEXT: SQL statement in PL/PgSQL function "diff" near line 4
Does any one help me to solve this problem. 有没有人能帮助我解决这个问题。
Try : 尝试:
date_part('year',age(coalesce(d1,current_date), d2))::int;
age(d1,d2)
function returns the number of years, months, and days between two dates in following format: age(d1,d2)
函数以以下格式返回两个日期之间的年,月和天数:
xxx year(s) xxx mon(s) xxx day(s).
from this output using date_part()
to pick the only the year difference. 使用
date_part()
从此输出中选择唯一的年份差。 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
并且也不需要放置if语句来处理
NULL
因为我已经添加了返回第一个NON Null
值的coalesece
,因此,如果d1
为NULL
则返回cuurent_date
Function Structure: 功能结构:
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;
Function Call: 函数调用:
select * from diff(null,'2010-04-01');
select * from diff('2012-10-01','2010-04-01');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.