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

如何在KDB+中更新列b,使其在值为3的行后2行递减1?

如何编写KDB+ Update语句实现指定行的列值递减

需求:更新表t的列b,在所有b值为3的行之后的连续2行中,将b的值逐行减1(即第一行设为2,第二行设为1)。

初始表构建代码

q)t: ([] a: raze 0b, 2# enlist(1b; 0b; 0b; 0b); b: 0)
q)t: update b: 3 from t where 0 = prev a, a

q)t
a b
---
0 0
1 3
0 0
0 0
0 0
1 3
0 0
0 0
0 0

解决方案

通过定位目标行的索引实现精准更新,步骤如下:

  1. 先找到所有b=3的行的索引:
    q)idx: where t.b=3
    
  2. 分别对b=3行的后第一行、第二行赋值:
    方式一(使用update语句):
    q)t: update b:2 from t where i in idx+1;
    q)t: update b:1 from t where i in idx+2;
    
    方式二(直接索引赋值,效率更高):
    q)t.b[idx+1]:2;
    q)t.b[idx+2]:1;
    

验证结果

执行后表t的内容如下,符合目标要求:

q)t
a b
---
0 0 
1 3
0 2
0 1
0 0
1 3
0 2
0 1
0 0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 22:22:38