Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kdb: dynamically denormalize a table (convert key values to column names)

Tags:

kdb+

I have a table like this:

q)t:([sym:(`EURUSD`EURUSD`AUDUSD`AUDUSD);server:(`S01`S02`S01`S02)];volume:(20;10;30;50))
q)t
sym    server| volume
-------------| ------
EURUSD S01   | 20    
EURUSD S02   | 10    
AUDUSD S01   | 30    
AUDUSD S02   | 50    

I need to de-normalize it to display the data nicely. The resulting table should look like this:

sym   | S01 S02
------| -------
EURUSD| 20  10 
AUDUSD| 30  50

How do I dynamically convert the original table using distinct values from server column as column names for the new table?

Thanks!

like image 540
derenik Avatar asked Jan 28 '26 05:01

derenik


1 Answers

Basically you want 'pivot' table. Following page has a very good solution for your problem: http://code.kx.com/q/cookbook/pivoting-tables/

Here are the commands to get the required table:

  q) P:asc exec distinct server from t
  q) exec P#(server!volume) by sym:sym from t
like image 184
Rahul Avatar answered Jan 30 '26 05:01

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!