【问题标题】:Changing a functional qSQL query to involve multiple columns in calculation KDB+/Q更改功能性 qSQL 查询以在计算 KDB+/Q 中涉及多个列
【发布时间】:2021-12-29 15:00:17
【问题描述】:

我有一个?像这样执行查询:

t:([]Quantity: 1 2 3;Price 4 5 6;date:2020.01.01 2020.01.02 2020.01.03);
?[t;enlist(within;`date;(2020.01.01,2020.01.02));0b;(enlist `Quantity)!enlist (sum;(`Quantity))]

让我得到给定日期范围内数量的总和。我想调整它以获得日期范围内 Notional 的总和;数量*价格。所以结果应该是(1x4)+(2x5)=14。

我尝试了以下方法

?[t;enlist(within;`date;(2020.01.01,2020.01.02));0b;(enlist `Quantity)!enlist (sum;(`Price*`Quantity))]

但无法让它工作。任何建议将不胜感激!

【问题讨论】:

    标签: kdb qsqlquery


    【解决方案1】:

    我建议在这种情况下考虑您正在寻找的 qSql 样式查询,然后从那里开始工作。

    所以在这种情况下,我相信你正在寻找类似的东西:

    select sum Quantity*Price from t where date within 2020.01.01 2020.01.02
    

    然后您可以在此运行 parse 以将其分解为函数形式,即 ?执行您所指的查询。

        q)parse"select sum Quantity*Price from t where date within 2020.01.01 2020.01.02"
    ?
    `t
    ,,(within;`date;2020.01.01 2020.01.02)
    0b
    (,`Quantity)!,(sum;(*;`Quantity;`Price))
    

    这是你需要的函数形式; table、where 子句、by 和聚合。

    您可以在此处看到您的数量只是两列相乘的总和。

    q)?[t;enlist(within;`date;(2020.01.01;2020.01.02));0b;enlist[`Quantity]!enlist(sum;(*;`Quantity;`Price))]
    Quantity
    --------
    14
    

    如果您愿意,您还可以扩展它以根据需要更改列并为其创建一个函数:

    q)calcNtnl:{[sd;ed] ?[t;enlist(within;`date;(sd;ed));0b;enlist[`Quantity]!enlist(sum;(*;`Quantity;`Price))]}
    q)calcNtnl[2020.01.01;2020.01.02]
    Quantity
    --------
    14
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多