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

如何在kdb中选取各sym组内最大值的下一条记录

在KDB中按分组选取最大值的下一条记录

解决方案代码

先处理原始数据得到展开后的表:

numm:1 2 3 4 5 6 5.5 4 3 
tab:([]sym:`a`b`c;time:(20:00:01 + til 9; 21:00:01 + til 9;22:00:02 + til 9);num:(numm;numm + 10;numm+ 100))
tab2:ungroup tab  // 展开嵌套表

直接通过分组筛选获取目标记录:

select from tab2 where i=(first i where num=max num)+1 by sym

代码解释

  • by sym:按sym字段分组,每组独立处理
  • first i where num=max num:在每组内定位num等于最大值的行索引(示例中每组最大值仅出现一次,first确保取到唯一索引)
  • (...) +1:获取最大值所在行的下一行索引
  • where i=...:筛选对应索引的行,即为每组最大值的下一条记录

运行后会得到预期结果:

sym time     num
----------------
a   20:00:07 5.5
b   21:00:07 15.5
c   22:00:08 105.5

备选分步实现

如果需要分步验证,可拆分为以下步骤:

  1. 为每组添加行号索引:
tab3:update idx:i by sym from tab2
  1. 计算每组最大值对应的目标索引:
targetIdx:select idx:first(i where num=max num)+1 by sym from tab3
  1. 筛选目标记录:
select sym, time, num from tab3 where (sym,idx) in flip targetIdx

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 06:09:24