如果我想在约会中添加5天,我可以使用INTERVAL
函数执行此操作:
select create_ts + interval '5 days' from abc_company;
但是,我的表有一个名为num_of_days
的字段,我想将它添加到我的create_ts中。像这样:
select create_ts + interval num_of_days || ' days' from abc_company;
这不起作用。我怎样才能在postgresql中完成这个?
答案 0 :(得分:9)
只需将值乘以间隔:
select create_ts + num_of_day * interval '1' day
from abc_company;
答案 1 :(得分:2)
你只需要一个工作类型转换。这种是标准的SQL。
select current_timestamp + cast((num_of_days || ' days') as interval)
from abc_company;
这是PostgreSQL特有的另一种语法。
select current_timestamp + (num_of_days || ' days')::interval
from abc_company;
我不想尝试记住PostgreSQL支持的第三种类型转换,这是类似函数的语法。
select current_timestamp + "interval" (num_of_days || ' days')
from abc_company;
为什么呢?因为some function names have to be quoted; interval 就是其中之一。
此外,名称间隔,时间和时间戳只能在此使用 如果它们是双引号的时尚,因为句法冲突。 因此,使用类似函数的强制转换语法 不一致,应该避免。
答案 2 :(得分:1)
here is a function that I use:
scala> consume(1 :: "asd" :: 3 :: HNil)
res0: Seq[String] = List(1-1-1, a-s-d, 3-3-3)
Used like so:
CREATE OR REPLACE FUNCTION DateAdd(diffType varchar(15), incrementValue int, inputDate timestamp) RETURNS timestamp AS $$
DECLARE
YEAR_CONST Char(15) := 'year';
MONTH_CONST Char(15) := 'month';
WEEK_CONST Char(15) := 'week';
DAY_CONST Char(15) := 'day';
HOUR_CONST Char(15) := 'hour';
dateTemp timestamp;
intervals interval;
BEGIN
IF lower($1) = lower(YEAR_CONST) THEN
select cast(cast(incrementvalue as character varying) || ' year' as interval) into intervals;
ELSEIF lower($1) = lower(MONTH_CONST) THEN
select cast(cast(incrementvalue as character varying) || ' months' as interval) into intervals;
ELSEIF lower($1) = lower(DAY_CONST) THEN
select cast(cast(incrementvalue as character varying) || ' day' as interval) into intervals;
ELSEIF lower($1) = lower(WEEK_CONST) THEN
select cast(cast(incrementvalue as character varying) || ' week' as interval) into intervals;
ELSEIF lower($1) = lower(HOUR_CONST) THEN
select cast(cast(incrementvalue as character varying) || ' hour' as interval) into intervals;
END IF;
dateTemp := inputdate + intervals;
RETURN dateTemp;
END;
$$ LANGUAGE plpgsql;
It supports adding years, months, weeks, days, hours. More support could be added