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

kdb/q技术实现:统计表中Name-Item列对买卖次数并筛选双交易组合

筛选kdb/q中同时存在Buy和Sell操作的Name-Item组合

原始数据定义

sample_data: ([] Name: `Ann`Ann`Ann`Bob`Bob`Bob`Bob; Item: `Apple`Apple`Bread`Apple`Salt`Salt`Salt; Action: `Buy`Sell`Sell`Buy`Buy`Buy`Sell; Price: 5.00 6.00 9.00 5.00 1.00 1.00 2.00)

需求说明

需要找出所有同时发生过至少一次Buy和Sell操作的Name-Item组合。


方法一:分两步实现(按计划生成中间表)

1. 生成统计中间表

按Name和Item分组,统计每组内Buy和Sell的操作次数:

stats_table: select Buys:count[i] where Action=`Buy, Sells:count[i] where Action=`Sell by Name, Item from sample_data

生成的中间表如下:

NameItemBuysSells
AnnApple11
AnnBread01
BobApple10
BobSalt21

2. 筛选符合条件的组合

从中间表中筛选Buys≥1且Sells≥1的记录,仅保留Name和Item列:

result: select Name, Item from stats_table where Buys >=1, Sells >=1

最终结果:

NameItem
AnnApple
BobSalt

方法二:一步到位实现

无需生成中间表,直接分组后检查每组是否同时包含Buy和Sell操作:

// 先按Name-Item分组去重Action,再筛选同时包含Buy和Sell的组
result: select Name, Item from (select distinct Action by Name, Item from sample_data) where all (`Buy`Sell) in Action

该方法逻辑更简洁,执行效率也更高,最终结果与方法一一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 11:52:39