SQL, 有终止条件的多次累计计算

MSSQL数据库的data表存储了多人上电梯的情况,turn表示进电梯的顺序。电梯最大承重1000公斤,每趟能上的人数有限,超重的人要等下一趟。

name

weight

turn

Alice

250

1

Bob

170

2

Alex

350

3

John

400

4

Winston

500

5

Marie

200

6

请计算每趟电梯最后一个进入的人的名字的列表。

Alex

Winston

Marie

编写SPL代码:


A

1

=sqlServer1.query("select * from data order by turn")

2

>cum=0

3

=A1.group@i(if( (cum+=weight)>1000, cum=weight, null))

4

=A3.(~.m(-1).name)

A1:用SQL取数,按turn排序

A2:给累计变量设初值

A3:按每趟电梯分组。当累计值大于 1000 时,开始新的分组,并将累计值重置为当前乘客体重。

A4:取每组的最后一条记录的 name 字段。

来源:https://stackoverflow.com/questions/78442803/list-of-all-the-last-people-to-enter-the-elevator