两个日期之间的月份功能

job*_*i88 10 postgresql function postgresql-9.1 postgresql-9.2

在oracle中我可以发现没有:使用MONTHS_BETWEEN函数之间的几个月.

在postgres我使用提取功能.eg.like

select 
    extract(year from age(current_date, '2012-12-09')) * 12
    + 
    extract(month from age(current_date, '2012-12-09'))
Run Code Online (Sandbox Code Playgroud)

在postgres中还有其他方法(内置函数)吗?

ara*_*nid 10

这很容易在PostgreSQL中重新实现,只需使用SQL函数来整理你已经拥有的东西:

create function months_of(interval)
 returns int strict immutable language sql as $$
  select extract(years from $1)::int * 12 + extract(month from $1)::int
$$;

create function months_between(date, date)
 returns int strict immutable language sql as $$
   select abs(months_of(age($1, $2)))
$$;
Run Code Online (Sandbox Code Playgroud)

现在select months_between('1978-06-20', '2011-12-09')生产401.

  • "月"是一个模糊的术语,不幸的是,当你在它周围包裹一个函数时,它不会变得模糊.使用`months_between('2012-01-01','2012-01-31')`在30天的间隔内返回0.但是使用`months_between('2012-02-01','2012-03-01')`会在29天的间隔内返回1.简短的故事是,您应该*在开始编写代码之前定义应用程序中"月"的含义. (6认同)
  • 我不知道.我赞成了araqnid的答案.根据我的经验,大多数使用此类功能的人*不会考虑*月*或*周数*应该在他们的应用程序中意味着什么.他们只是使用他们发现的东西.(这是观察,而不是批评.)OP没有接受答案,所以我希望他或她迟早会阅读所有这些内容.也许我不切实际地乐观. (4认同)

Boh*_*ian 3

不幸的是,似乎不是,因为返回模 12extract(month ...)的月数。

您可以做一个小小的简化;删除第一个参数age()- 默认是年龄current_date,所以这两个是等价的:

age(current_date, '2012-12-09')
age('2012-12-09')
Run Code Online (Sandbox Code Playgroud)