【问题标题】:Difference between two dates in postgresqlpostgresql中两个日期之间的差异
【发布时间】:2016-02-03 05:11:37
【问题描述】:

功能:

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;

我的要求是找出两个日期之间的年差。所以,我写了上面的函数。在这里,如果 d1 为 NULL,则为它分配当前日期。但是,它会产生如下所示的错误。

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 

有没有人帮我解决这个问题。

【问题讨论】:

  • 您是否尝试删除 SELECT ? RETURN extract(year from age(d1,d2));
  • 除了 Jay 的评论之外,另一个潜在问题可能是 AGE() 没有返回 extract() 可以处理的日期类型。
  • @JayKumarR 根据您的建议,函数创建成功。但是,它没有给出预期的输出。如果 d1 为 null,则返回 NULL 作为输出。

标签: sql postgresql date sql-date-functions


【解决方案1】:

试试:

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

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

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

使用date_part() 从此输出中选择唯一的年份差异。也不需要使用 if 语句来处理 NULL,因为我添加了 coalesece,它返回第一个 NON Null 值,所以如果 d1NULL 它返回 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');

【讨论】:

  • 它显示错误,例如“错误:“) 处或附近的括号不匹配”第 7 行:返回 date_part('year',age(d1,current_date), d2))::int; ^
  • 分享你创建的函数。
  • 这对我有用。请检查更新的答案。
  • CREATE FUNCTION diff(d1 date,d2 date) RETURNS int AS $$ BEGIN IF d1 = NULL THEN RETURN extract(year from age(current_date,d2)); ELSE RETURN extract(year from age(d1,d2)); END IF; END $$ language plpgsql;
  • @mrg:按照答案创建函数,无需检查NULL 值。
猜你喜欢
  • 1970-01-01
  • 2016-10-31
  • 2011-10-29
  • 1970-01-01
  • 2020-10-19
  • 2013-10-02
  • 2012-01-15
  • 2016-12-30
  • 2011-06-13
相关资源
最近更新 更多