kdbqsqlquery

How to create a variable dependent column name?


I am struggling to name a column based on a variable.

I want to create a column with a name including the stock symbol, for example Open_AAPL, Open_MSFT, Open_ORCL.

I have tried the following to make the column name Open_AAPL:

sym: `AAPL
column_name: `$""sv string (`Open_,sym) //merge the symbols (this becomes `Open_AAPL)
t1: select `column_name: first last_trade by date from t

and

t1: select column_name: first last_trade by date from t

which do not work. How can I do this? The reason for doing this is to create a function where I just need to input the different symbols and the column name changes.


Solution

  • Use a functional select if you require column names that are dynamically produced:

    q)trade:([]sym:`AAPL`AAPL;last_trade:100 101)
    q)select Open_AAPL:first last_trade from trade
    Open_AAPL
    ---------
    100
    q)parse"select Open_AAPL:first last_trade from trade"
    ?
    `trade
    ()
    0b
    (,`Open_AAPL)!,(*:;`last_trade)
    q){?[trade;();0b;enlist[`$"Open_",string x]!enlist(first;`last_trade)]}`AAPL
    Open_AAPL
    ---------
    100