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

kdb/q中如何关联两表计算销售统计字段?是否为内连接?

原始销售记录表(sales_data)

NameItemActionPriceNum_Items
AnnAppleBuy5.0010
AnnAppleSell6.0012
AnnBreadSell9.009
BobAppleBuy5.0014
BobSaltBuy1.0010
BobSaltBuy1.001
BobSaltSell2.002

对应的KDB+定义代码:

sales_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; Num_Items: 10 12 9 14 10 1 2)

筛选后的Name-Item对(distinct_data)

NameItem
AnnApple
BobSalt

对应的KDB+定义代码:

distinct_data: ([] Name: `Ann`Bob; Item: `Apple`Salt)

目标表

NameItemNum_BuyNum_SoldWeighted_Avg_Price_BoughtWeighted_Avg_Price_Sold
AnnApple101256
BobSalt11212

关联实现方法

在KDB+中可以通过分组聚合+等值连接完成需求,具体步骤如下:

  1. 先对sales_data按Name和Item分组,计算所需的聚合字段:
agg_sales: select 
    Num_Buy: sum Num_Items where Action=`Buy,
    Num_Sold: sum Num_Items where Action=`Sell,
    Weighted_Avg_Price_Bought: sum[Price*Num_Items where Action=`Buy] % sum[Num_Items where Action=`Buy],
    Weighted_Avg_Price_Sold: sum[Price*Num_Items where Action=`Sell] % sum[Num_Items where Action=`Sell]
by Name, Item from sales_data
  1. 将distinct_data与聚合后的agg_sales做内连接,保留目标Name-Item对的聚合结果:
target_table: distinct_data lj `Name`Item xkey agg_sales

也可以合并为一步,直接在连接时完成分组聚合:

target_table: select 
    Num_Buy: sum Num_Items where Action=`Buy,
    Num_Sold: sum Num_Items where Action=`Sell,
    Weighted_Avg_Price_Bought: sum[Price*Num_Items where Action=`Buy] % sum[Num_Items where Action=`Buy],
    Weighted_Avg_Price_Sold: sum[Price*Num_Items where Action=`Sell] % sum[Num_Items where Action=`Sell]
from distinct_data, sales_data where distinct_data.Name=sales_data.Name, distinct_data.Item=sales_data.Item
group by distinct_data.Name, distinct_data.Item

连接类型判断

这个场景属于内连接。因为最终结果只保留了同时存在于distinct_data和sales_data中的Name-Item对,完全符合内连接“仅保留两张表中匹配成功的行”的定义。

内容的提问来源于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 12:01:34