postgresql - 用于加载年度数据的 postgres 函数
问题描述
我有 2 个功能:第一个是接收日期参数的月份数据(任何月份的最后日期),这是截断和加载。第二个是使用上述功能在年表中附加数据的年数据。参数是月数(例如,如果参数为 12,则应为过去 12 个月,如果为 6,则应为过去 6 个月)对于我们的示例,其为 12。
函数 1 调用如下:
select * from fn_monthly('2021-08-31')
对于第二个功能,我们基本上需要根据月份参数进行迭代并执行该功能。其定义如下:
CREATE OR REPLACE FUNCTION fn_yearly(in months int)
RETURNS character varying
LANGUAGE plpgsql
AS $function$
v_months int = (months*-1)+2;
v_date date;
begin -- executes all code including exception logic
begin -- returns success if no exception
truncate table yearly_table;
for counter in reverse 1..v_months loop
v_date := (Date_trunc('month', CURRENT_DATE) + interval '% month - 1 day',counter)::date;
-- this should put last date of month in variable v_date
-- example when counter is 1, then v_date = '2021-08-31'
-- example when counter is 0, then v_date = '2021-07-31'
-- example when counter is -1, then v_date = '2021-06-30'
--this is the date I needs to pass into the monthly function
select * from fn_monthly(v_date);
insert into yearly_table(col1,col2) select col1,col2 from monthly_table;
end loop;
end; -- returns success if no exception
$function$
;
当我执行上述函数时,出现以下错误:
ErrorCode:42846, ErrorMsg:cannot cast type record to date
解决此问题的最佳方法是什么?也许其他一些方法。
解决方案
错误与此表达式有关:
(Date_trunc('month', CURRENT_DATE) + interval '% month - 1 day',counter)::date
您想格式化间隔,'% month - 1 day',counter
但在这种情况下语法不可接受,请使用:
(Date_trunc('month', CURRENT_DATE) + interval '1 month'* counter - interval '1 day')::date
推荐阅读
- c - C 转换结构的返回值
- jquery - jQuery 外部函数参数在每个循环中不可见
- node.js - 当graphQL的查询从mongodb返回空数据时,你应该检查什么?
- html - 尽管自动溢出,flexbox 的内容仍然溢出
- sql-server - SQL Server:将旧 ID 更新为新 ID(UPDATE 中的 SELF JOIN)
- visual-studio - 生成的数据库与我的 edmx 架构不匹配
- reactjs - 在 lefalet 中创建新形状图层时如何删除最后一个形状图层
- docker - 重新启动后,docker-compose 服务无法通过 systemctl 自动启动
- html - 将多个 tab_model html 对象保存到 1 个文件中(例如,PDF、Word 或 html 文件)
- .net - MATLAB 无法调用 .NET 库进行机器人控制