Search code examples
kdb

Passing a column name as an argument for KDB select query?


I would like to pass a column name into a Q function to query a loaded table.

Example:

getDistinct:{[x] select count x from raw}
getDistinct "HEADER"

This doesn't work as the Q documentation says I cannot pass column as arguments. Is there a way to bypass this?


Solution

  • When q interprets x it will treat it as a string, it has no reference to the column, so your output would just be count "HEADER".

    If you want to pass in the column as a string you need to build the whole select statement then use value

    {value "select count  ",x," from tab"} "HEADER"
    

    However, the recommended method would be to use a functional select. Below I use parse to build the functional select equivalent using the parse tree.

    /Create sample table
    tab:([]inst:10?`MSFT`GOOG`AAPL;time:10?.z.p;price:10?10f)
    
    /Generate my parse tree to get my functional form
    .Q.s parse "select count i by inst from tab"
    
    /Build this into my function
    {?[`tab;();(enlist x)!enlist x;(enlist `countDistinct)!enlist (#:;`i)]} `inst
    

    Note that you have to pass the column in as a symbol. Additionally the #:i is just the k equivalent to count i.

    Update for multiple columns

    tab:([]inst:10?`MSFT`GOOG`AAPL;time:10?.z.p;price:10?10f;cntr:10`HK`SG`UK`US)
    {?[`tab;();(x)!x;(enlist `countDistinct)!enlist (#:;`i)]} `inst`cntr