如何累计求和

这篇博客讨论了如何在SQL和SPL中实现对特定时间范围内的数据进行跨行累计求和。提供了两种方法,一种是利用SQL的变量来逐行累加A和B列的值,另一种是使用SPL的跨行操作实现相同功能。内容详细解释了每种方法的实现步骤,并给出了具体的SQL和SPL代码示例。
摘要由CSDN通过智能技术生成

【问题】

I have SQL table which has 3 columns like this

entry_time          |  A        | B      |
-------------------------------------------
2015-06-05 18:44:56 |  10       |  8     |
2015-06-06 16:04:36 |  -5       | -2     |
2015-06-07 10:01:14 |   3       |  1     |

I want to get the sum of A and B columns up to particular given time stamp like below.

 status at given date |  A        | B      |
 -------------------------------------------
 2015-06-05 23:59:59 |  10       |  8     |
 2015-06-06 23:59:59 |   5       |  6     |
 2015-06-07 23:59:59 |   8       |  7     |

I thought using of between. But as I am giving the date I want totals from front end without seeing of data table and its first records date, is there any way to solve this.Please help me.

有人给出答案:

select
entry_time,
a_sum as A,
b_sum as B from(
  select
  entry_time,
  @A_sum:= @A_sum + A as a_sum,
  @B_sum:= @B_sum + B as b_sum
  from table_name,(select @A_sum:=0,@B_sum:=0)x
  order by entry_time
)x

【回答】

上面通过变量,sql实现很容易,下面是SPL的实现方法,跨行累计更直观:

A
1$ select entry_time,A,B from tb order by entry_time
2=A1.run(A=A[-1]+A,B=B[-1]+B)

A1:sql取数,按照entry_time排序

A2:跨行累加,对A,B列重新赋值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值