Search code examples
kdb

Functional q-SQL: How to translate the fby part of the parse tree


When I run parse"select from trade where date=max date,price=(max;price) fby sym"

I get the following parse tree:

</br>

?

`trade

,((=;`date;(max;`date));(=;`price;(k){$[(#x 1)=#y;@[(#y)#x[0]0#x 1;g;:;x[0]'x..

0b

()

I tried interpreting this in functional form as:

?[trade;((=;`date;(max;`date));(=;`price;(k){$[(#x 1)=#y;@[(#y)#x[0]0#x 1;g;:;x[0]'x..;0b;()]

but I get an error pointing to the final. What is wrong with my syntax?


Solution

  • You have two issues here. First is that your display window is not wide enough to show the full output. To adjust this window use \c (console size) command:

    q)\c 25 200
    q)parse"select from trade where date=max date,price=(max;price) fby sym"
    ?
    `trade
    ,((=;`date;(max;`date));(=;`price;(k){$[(#x 1)=#y;@[(#y)#x[0]0#x 1;g;:;x[0]'x[1]g:.=y];'length]};(enlist;max;`price);`sym)))
    0b
    ()
    

    However, you will still have an issue using this because parse displays the full underlying k definition of fby:

    q)fby
    k){$[(#x 1)=#y;@[(#y)#x[0]0#x 1;g;:;x[0]'x[1]g:.=y];'length]}
    

    Note that the definition is prefixed with "k)", which causes the error. To get around this you'll want to entirely replace the the k definition above with fby so that you have

    ?[trade;((=;`date;(max;`date));(=;`price;(fby;(enlist;max;`price);`sym)));0b;()]
    

    rather than

    ?[trade;((=;`date;(max;`date));(=;`price;(k){$[(#x 1)=#y;@[(#y)#x[0]0#x 1;g;:;x[0]'x[1]g:.=y];'length]};(enlist;max;`price);`sym)));0b;()]