5.3 数据无序,保持原序时计算某列与上一日期的差值
Sybase 数据库中有表 SAMPLE,数据如下所示:
SECURITY_ID | DATE | REP |
---|---|---|
2256 | 2020-01-01 | 0 |
2257 | 2020-01-02 | 1 |
2258 | 2020-01-03 | 2 |
2256 | 2020-01-02 | 3 |
2256 | 2020-01-03 | 5 |
需要在保持原表次序不变的情况下,计算相同 SECURITY_ID 下 REP 列与上一天的差值(DIFF),结果如下:
SECURITY_ID | DATE | REP | DIFF |
---|---|---|---|
2256 | 2020-01-01 | 0 | 0 |
2257 | 2020-01-02 | 1 | 1 |
2258 | 2020-01-03 | 2 | 2 |
2256 | 2020-01-02 | 3 | 3 |
2256 | 2020-01-03 | 5 | 2 |
按原顺序,SECURITY_ID 相同时,求当前日期的 REP 与上一日 REP 的差值。
脚本:
A | |
---|---|
1 | =connect(“demo”) |
2 | =A1.query@x(“SELECT * FROM SAMPLE”).derive(null:DIFF) |
3 | >A2.group(SECURITY_ID).(~.run(DIFF=REP-REP[-1])) |
4 | return A2 |
A3 按 SECURITY_ID 分组后计算当前日期的 REP 与上一日 REP 的差值,分组后的子集是对原序表记录的引用,所以写入 DIFF 时,其实是往原序表的 DIFF 里写
A4 返回原序表,这样不会改变原序表的顺序