【问题标题】:Subtracting numeric from date in Postgresql从 Postgresql 中的日期中减去数字
【发布时间】:2021-10-07 13:38:36
【问题描述】:

当我执行这些脚本时,它在 postgresql 中运行;

select '2021-09-01'::Date - 1

select current_date -1 

但是当我在函数中使用这种类型的减法时,postgresql 会给我这样的错误;

声明部分的函数用法:

v_date date := p_date - p_number;
ERROR:  operator does not exist: date - numeric

【问题讨论】:

  • 如果您以p_number 的身份通过3.14,您期望什么结果?
  • 该函数不会以十进制数作为输入,所以我对3.14没有任何期望。所以“v_date date := p_date - p_number::int;”为我工作。
  • 更简洁的解决方案是将参数声明为int

标签: postgresql date numeric subtraction


【解决方案1】:

试试:

v_date date := p_date - p_number::int;.

对于Date/Time Operators,您只能从日期中减去整数、间隔或日期。

注意::int 转换会将数字四舍五入。

更新

另一种选择是让p_number 从一开始就为整数,但这取决于它是否用于需要为数字的其他用途。

【讨论】:

  • 谢谢你,它有效:)
  • 查看更新以获得替代解决方案。
猜你喜欢
  • 1970-01-01
  • 2012-10-07
  • 2016-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-25
相关资源
最近更新 更多