使用 dateadd 在日期中添加月份

Adding months to a date with dateadd

我有一组看起来与此类似的数据:

我想做的是创建第三个字段,我们称之为 length,它采用 created_date 字段并为您提供基于 created_date + months[ 的日期字段=16=]

所以实际上,第三列看起来像这样

但是当我尝试我查找的方式时,它给了我一个错误:

SELECT
DATEADD('month', months, DATE(created_date)) 
FROM
table

ERROR: function date_add(unknown, double precision, date) does not exist
  Hint: No function matches the given name and argument types. You might need to add explicit type casts.

我只是使用了错误类型的语法,我应该使用不同的函数吗?

注意:根据错误消息,我假设您使用的是 Postgres。


您可以 add 一个 interval 直接到一个 date 值。由于你有一个固定的单位,使用 make_interval() 是最简单的方法:

SELECT date_created + make_interval(months => "months"::integer)
FROM the_table

强制转换为 integer 是必要的,因为您不能使用该函数指定小数月份。如果你真的需要那个,那么将值乘以一个月的间隔:

SELECT date_created + months * interval '1 month'
FROM the_table

一般来说,我会建议将 months 列更改为 interval,这样您就不必担心这些事情了。