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

Oracle SQL实现每行与后续3行的求和计算求助

Oracle SQL 计算当前行及后续2行的数值之和

需求说明

需要计算每行数值与其后2行数值的总和(共3行),当后续不足2行时返回NULL,示例如下:

ID  VALUE1  期望结果
===================
1   10   10+5+20 = 35
2   5    5+20+4  = 29
3   20   20+4+50 = 74
4   4    4+50+300 = 354
5   50   50+300+10 = 360
6   300  300+10+15 = 325
7   10   NULL
8   15   NULL

错误分析

你当前使用的GROUP BY value是按数值分组求和,完全无法实现行级的连续范围求和,所以得不到预期结果。

解决方案

需要使用Oracle的窗口函数SUM() OVER(),结合行号来指定求和的行范围,同时判断是否满足足够的后续行数来返回结果:

with dummy as (
   select 10 as value from dual union all
   select 5 from dual union all
   select 20 from dual union all
   select 4 from dual union all
   select 50 from dual union all
   select 300 from dual union all
   select 10 from dual union all
   select 15 from dual 
),
-- 生成带行号的数据集,确保顺序正确
ranked_data as (
   select 
       row_number() over (order by null) as id, -- 按union all的插入顺序生成行号
       value
   from dummy
),
-- 计算总行数,用于判断后续行是否足够
total_rows as (
   select count(*) as cnt from ranked_data
)
select 
    id,
    value,
    -- 仅当当前行号 <= 总行数-2时,返回求和结果,否则返回NULL
    case when id <= (select cnt from total_rows) - 2 
         then sum(value) over (order by id rows between current row and 2 following)
         else null
    end as expected_result
from ranked_data
order by id;

代码说明

  1. ranked_data:用row_number()生成连续行号,保证数据顺序与示例中的ID对应(若需要更稳定的排序逻辑,建议添加明确的排序字段替代order by null)。
  2. total_rows:统计数据集的总行数,用于判断当前行是否有足够的后续行。
  3. SUM() OVER(rows between current row and 2 following):精准计算当前行到后续2行的数值总和。
  4. case语句:当后续不足2行时返回NULL,完全匹配示例的期望结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 03:32:45