Search code examples
kdb

Write a Q-SQL query to multiply the price of BA.N by 2, GS.N by 3 and MSFT.O by 4 and call the column newPrice using vector conditional statement


Write a Q-SQL query to multiply the price of BA.N by 2, GS.N by 3 and MSFT.O by 4 and call the column newPrice using vector conditional statement

tab2:`syms`prices!(`MSFT.O`GS.N`BA.N;45.15 191.10 178.50)
flip tab2

select syms,prices,newPrice:(prices*(4,3,2)) from flip tab2

Solution

  • I'm not sure using a vector conditional would be the easiest way to go about this. For example, you could use a simple dictionary to achieve a similar effect. First define a dictionary mapping your syms to their multipliers then use that dictionary in your select statement:

    tab2: flip `syms`prices!(`MSFT.O`GS.N`BA.N;45.15 191.10 178.50)
    d: `MSFT.O`GS.N`BA.N!4 3 2;
    
    select syms, prices, newPrice: prices*d[syms] from tab2
    syms   prices newPrice
    ----------------------
    MSFT.O 45.15  180.6
    GS.N   191.1  573.3
    BA.N   178.5  357
    

    Vector conditionals can only return one of two results, depending on if the condition is true or false. To extend that limitation to what you want you could nest the conditionals inside each other. So like:

    select syms, prices, newPrice: ?[syms=`MSFT.O; prices*4; ?[syms=`GS.N; prices*3; ?[syms=`BA.N;prices*2;prices]]] from tab2
    

    But this quickly becomes unwieldy and doesn't scale well. If you added more syms, it would be easy to update the dictionary, but annoying to update the conditional.