Search code examples
kdb

Is there a quick way to inner join symbols in a single query?


Currently, say I have a database with sym-date rows.

If I want to extract two series and align them on date, I currently have to do two queries and then join them:

pair: {[x;y]
  aa: select date, a: target1 from z where sym = x;
  bb: select date, b: target1 from z where sym = y;
  1!aa ij 1!bb
  }

corr[`AAPL;`MSFT]

Is there a more elegant way to do this in KDB?


Solution

  • It looks like you essentially want to pivot the data? https://code.kx.com/q/kb/pivoting-tables/

    q)t:([]date:2021.01.01 2021.01.01 2021.01.01;sym:`AAPL`MSFT`TSLA;target1:1.1 2.2 3.3)
    q)P:`AAPL`MSFT
    q)exec P#(sym!target1) by date:date from t
    date      | AAPL MSFT
    ----------| ---------
    2021.01.01| 1.1  2.2