kdb+k

Parse tree built on values from vars


We can group by several columns in kdb+:

q)t:([]a:1 1 3;b:1 1 4;c:7 8 9);
q)select sum c by grp:([]a;b) from t
grp     | c
--------| --
`a`b!1 1| 15
`a`b!3 4| 9
q)gcols:`a`b

But how to do the same with a functional form (how to build a correct parse tree) if desired columns to group by are in a variable gcols?


Solution

  • The more conventional group by would be:

    q)select sum c by a,b from t
    a b| c
    ---| --
    1 1| 15
    3 4| 9
    

    for which the functional form would be

    q)?[t;();{x!x}gcols;(1#`c)!enlist(sum;`c)]
    a b| c
    ---| --
    1 1| 15
    3 4| 9
    

    The functional form for your style of grouping would be:

    q)?[t;();(1#`grp)!enlist(flip;(!;enlist gcols;enlist,gcols));(1#`c)!enlist(sum;`c)]
    grp     | c
    --------| --
    `a`b!1 1| 15
    `a`b!3 4| 9