Search code examples
kdbqsqlquery

Q/KDB+ Create new column through a query


I have data in a table where there are "Buys" and "Sells" alongside the Quantity. I want query so that if it equals a "SELL" i multiply the Quantity column to negative. so far i am just selecting the data and taking from a certain timeframe. Nothing complex.


Solution

  • Using the update functionality along with the where clause you can edit a column in a table using certain filters. In this case the filter is where side=SELL.

    If you add a backtick to the table name in the update statement this will update the table in place.

    q)tab:([]time:10:00 12:00 13:00 14:00;side:`BUY`SELL`BUY`SELL;qty:300 400 300 500)
    q)tab
    time  side qty
    --------------
    10:00 BUY  300
    12:00 SELL 400
    13:00 BUY  300
    14:00 SELL 500
    q)update qty:neg qty from tab where side=`SELL
    time  side qty
    ---------------
    10:00 BUY  300
    12:00 SELL -400
    13:00 BUY  300
    14:00 SELL -500
    

    Updating in place:

    q)update qty:neg qty from `tab where side=`SELL
    `tab
    q)tab
    time  side qty
    ---------------
    10:00 BUY  300
    12:00 SELL -400
    13:00 BUY  300
    14:00 SELL -500