KDB/Q:按组计算百分比
KDB/Q: compute the percentage by group
有没有快速获取组中每个项目的 proportion/percentage 的方法?现在,我首先按组计算值的总和,然后将这个总数table合并到原来的table,然后计算比例。 Q 有快速计算这个的函数吗?
day week item proportion
mon 1 2 20%
tue 1 7 70%
wed 1 1 10%
mon 2 1 25%
tue 2 2 50%
wed 2 1 25%
目前,我会做:
total: select total: sum item by week from table;
out: update proportion: item%total from table lj `week xkey total;
您可以使用 fby
在一个查询中执行此操作:
q)table:flip`day`week`item!(`mon`tue`wed`mon`tue`wed;1 1 1 2 2 2;2 7 1 1 2 1)
q)update proportion:item % (sum;item) fby week from table
day week item proportion
------------------------
mon 1 2 0.2
tue 1 7 0.7
wed 1 1 0.1
mon 2 1 0.25
tue 2 2 0.5
wed 2 1 0.25
有没有快速获取组中每个项目的 proportion/percentage 的方法?现在,我首先按组计算值的总和,然后将这个总数table合并到原来的table,然后计算比例。 Q 有快速计算这个的函数吗?
day week item proportion
mon 1 2 20%
tue 1 7 70%
wed 1 1 10%
mon 2 1 25%
tue 2 2 50%
wed 2 1 25%
目前,我会做:
total: select total: sum item by week from table;
out: update proportion: item%total from table lj `week xkey total;
您可以使用 fby
在一个查询中执行此操作:
q)table:flip`day`week`item!(`mon`tue`wed`mon`tue`wed;1 1 1 2 2 2;2 7 1 1 2 1)
q)update proportion:item % (sum;item) fby week from table
day week item proportion
------------------------
mon 1 2 0.2
tue 1 7 0.7
wed 1 1 0.1
mon 2 1 0.25
tue 2 2 0.5
wed 2 1 0.25