解释起来很困难,我想对每一行的最后 3 行求和。举个例子就更好了:
ID VALUE1 RESULT I WANT
===================
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
我使用 Oracle SQL。谢谢
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
)
SELECT value, SUM(value) FROM dummy GROUP BY value
我不知道如何处理
您可以使用 Oracle 函数“当前行和后续 2 行之间的行” https://learnsql.com/blog/sql-window-functions-rows-clause/,如下。
with dummy as
(
select 1 as id, 10 as value from dual union all
select 2 ,5 from dual union all
select 3, 20 from dual union all
select 4, 4 from dual union all
select 5, 50 from dual union all
select 6, 300 from dual union all
select 7, 10 from dual union ALL
select 8, 15 from dual
)
SELECT value, value, sum(value)
OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING) sum
FROM dummy;