首页 > 解决方案 > fby q/kdb 聚合函数

问题描述

我想申请fbyusing count distinct,即

select from t where 1=(count distinct; column) fby another_column

我怎样才能做到这一点?

标签: kdb

解决方案


要添加到已经存在的内容,您可以使用 @apply 以更少的字符执行此操作

q)n:100
// Create a table where all entries for sym=`a are size 10
q)show t:update size:10 from ([]sym:n#`a`b`c`d;size:n?200) where sym = `a
sym size
--------
a   10
b   28
c   51
d   64
a   10
b   43
...
// Use count distinct@ to select from the table as per your requirements
q)select from t where 1=(count distinct@;size) fby sym
sym size
--------
a   10
a   10
a   10
a   10
a   10

0N!是检查这些查询“飞行中”的操作的好运算符
使用它我们可以看到count distinct它自己的失败,因为它试图计算distinct返回 1的函数

q)select from t where 1=(0N!count distinct; size) fby sym
1
'type
  [0]  select from t where 1=(0N!count distinct; size) fby sym

但是使用 dyadic @ 我们可以创建一个方便的投影

q)select from t where 1=(0N!(count distinct@); size) fby sym
#@[?:]
sym size
--------
a   10
a   10
a   10
a   10
...

在这里,我不得不在这里用括号括起来以防止 0N!被吸入count distinct @投影。在 k-speak 中,这有效地转化为“计算应用于 @ 的第二个参数的不同运算符的结果”。代码打高尔夫球非常方便


推荐阅读