How can I have a conditional sum in kdb, something like the following sql query
Select sum(qty > 0, qty, 0) as buy, sum(qty < 0, qty, 0) as sell from trades
I am looking for a way to do this without any where clause.
How can I have a conditional sum in kdb, something like the following sql query
Select sum(qty > 0, qty, 0) as buy, sum(qty < 0, qty, 0) as sell from trades
I am looking for a way to do this without any where clause.
You can achieve this using a lambda function inline on your select statement:
q)trades:([]sym:`a`b`c`d`e`f`g;qty:-34 -27 -11 50 19 -30 1)
q)select buy:sum {x where 0<x}[qty], sell:sum {x where 0>x}[qty] from trades
buy sell
--------
70 -102
Better method (with conditional):
q)select buy:sum ?[qty>0;qty;0], sell:sum ?[qty<0;qty;0] from trades
buy sell
--------
70 -102
Using 'min' and 'max' operators:
q)select buy:sum qty|0f,sell:sum qty&0f from trades
buy sell
--------
70 -102
I would follow the first method proposed by @davidcrossey, but would simplify code a bit and remove anonymous functions:
select buy: sum qty where qty > 0, sell: sum qty where qty < 0 from trades
This query is preferable, because ?[;;]
works slower and consumes more space (~ 2 times). min/max
approach is probably faster but consumes x2 space as well. You may use next code as performance test, \ts
returns time space
used by the query
trades: enlist[`qty]!enlist -50 + 1000000?100;
\ts select buy: sum qty where qty > 0, sell: sum qty where qty < 0 from trades
// returns 43 8389424
\ts select buy:sum ?[qty>0;qty;0], sell:sum ?[qty<0;qty;0] from trades
// returns 68 17826560
\ts select buy:sum qty|0f,sell:sum qty&0f from trades
// returns 39 16777856
In this case <
& >
are acting as vector conditional operators, hence passing the full columns works. However, there are cases where a function needs the inputs as atoms, in that case, each
can be used.
q)trades:([]sym:`a`b`c`d`e`f`g;qty:-34 -27 -11 50 19 -30 1)
q)select buy:sum qty where {0<x}each qty, sell:sum qty where {0>x} each qty from trades
buy sell
--------
70 -102
You can now replace {0<x}
to some more complex function that takes atoms as parameters and it should work fine.