You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Oracle数据库按月、季度统计租金的存储过程开发咨询

Oracle 存储过程调整方案

原代码问题分析

  • 原GROUP BY ROLLUP(money)逻辑完全不匹配需求,无法按时间维度分组统计
  • 输入参数c_id/RS/RE无需设置为IN OUT,仅需IN类型即可,只有结果游标需要返回值
  • 没有提取时间维度的月份、季度字段,无法做维度聚合
  • 参数名和表字段重名,会导致Oracle优先解析为表字段,过滤条件c_id = rent.car_id实际等同于没加限制

调整后完整代码

create or replace procedure p_money
(
    p_c_id     in  rent.car_id%TYPE,
    p_rs       in  rent.rent_start%TYPE,
    p_re       in  rent.rent_start%TYPE,
    v_result   out sys_refcursor
)
as
begin
  open v_result for
  select
    'month_1 - ' || sum(case when month_seq = 1 then money else 0 end) as month_1,
    'month_2 - ' || sum(case when month_seq = 2 then money else 0 end) as month_2,
    'month_3 - ' || sum(case when month_seq = 3 then money else 0 end) as month_3,
    'quarter - ' || sum(money) as quarter
  from (
    select
      money,
      -- 计算当前记录属于输入时间范围内的第几个月,兼容跨年场景
      floor(months_between(trunc(rent_start, 'month'), trunc(p_rs, 'month'))) + 1 as month_seq
    from rent 
    where 
      car_id = p_c_id 
      and rent_start between p_rs and p_re 
      and rent_end between p_rs and p_re
  ) t
  where month_seq <=3;
end p_money;

逻辑说明

  • 输入参数统一加p_前缀,避免和表字段重名导致过滤条件失效
  • 内层查询先计算每条记录属于输入时间范围的第几个月,适配不同季度起止时间的统计需求
  • 外层用条件聚合直接按月份序号统计对应月份的总金额,同时直接统计季度总金额,无需额外分组
  • 输出结果直接按照你要求的month_1 - x格式拼接字符串,返回一行四列的结果,完全匹配预期输出
  • 如果你需要返回数值类型而非拼接好的字符串,删掉'month_1 - ' ||这类前缀拼接逻辑即可
  • 如果需要按自然月序号命名(比如1月固定对应month_1,和输入起始时间无关),把内层的month_seq计算逻辑改为extract(month from rent_start)即可

内容的提问来源于stack exchange,提问作者Mcmuffinstar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 18:06:02