Search code examples
kdb

Storing output of a iterating function into unique tables KDB+/Q


I have a query function of the format:

function:{[x] select Y from table1 where date=x}

I want to iterate this function across all days stored in a separate table, like so

function each (select distinct date from table2)

and store every iteration into it's own, unique table. For example, if the first iteration was for 2021.11.10, all 'Y' values from table1 on that date are stored in a table named 'a', for the next iteration for date 2021.11.12, it goes to a table named 'b', or something like that. How can I do this?


Solution

  • Assume the following tables:

    q)t1:([]date:.z.d + 0 0 0 1 1 1;a:1 2 3 4 5 6)
    q)t2:([]date:.z.d+0 1)
    

    then you could do something like:

    q)function:{[x;y] x set select from t1 where date=y}
    q)function'[`a`b;exec distinct date from t2]
    `a`b
    q)show a
    date       a
    ------------
    2021.11.10 1
    2021.11.10 2
    2021.11.10 3
    q)show b
    date       a
    ------------
    2021.11.11 4
    2021.11.11 5
    2021.11.11 6
    

    If you wanted to make it a bit more dynamic then you could also do something like:

    q)function:{[x] (`$"tab",string[x] except ".") set select from t1 where date=x}
    q)
    q)
    q)function each exec distinct date from t2
    `tab20211110`tab20211111
    q)show tab20211110
    date       a
    ------------
    2021.11.10 1
    2021.11.10 2
    2021.11.10 3
    q)show tab20211111
    date       a
    ------------
    2021.11.11 4
    2021.11.11 5
    2021.11.11 6
    

    The above creates new tables named for each date (we remove the "." from the resulting names as they could be confused for q's . operator)