3

I have a table rCom which has various columns. I would like to sum across each row..

for example:

Date TypeA TypeB TypeC TypeD

date1 40.5 23.1 45.1 65.2

date2 23.3 32.2 56.1 30.1

How can I write a q query to add a fourth column 'Total' that sums across each row?

Daniel Krizian
  • 4,586
  • 4
  • 38
  • 75
stretchr
  • 615
  • 2
  • 9
  • 24

4 Answers4

2

why not just:

update Total: TypeA+TypeB+TypeC+TypeD from rCom

?

Manish Patel
  • 4,411
  • 4
  • 25
  • 48
2

Sum will work just fine:

q)flip`a`b`c!3 3#til 9
a b c
-----
0 3 6
1 4 7
2 5 8
q)update d:sum(a;b;c) from flip`a`b`c!3 3#til 9
a b c d
--------
0 3 6 9
1 4 7 12
2 5 8 15

Sum has map reduce which will be better for a huge table.

WooiKent Lee
  • 1,301
  • 6
  • 4
1

One quick point regarding summing across rows. You should be careful about nulls in 1 column resulting in a null result for the sum. Borrowing @WooiKent Lee's example.

We put a null into the first position of the a column. Notice how our sum now becomes null

q)wn:.[flip`a`b`c!3 3#til 9;(0;`a);first 0#] //with null
q)update d:sum (a;b;c) from wn
a b c d
--------
  3 6
1 4 7 12
2 5 8 15

This is a direct effect of the way nulls in q are treated. If you sum across a simple list, the nulls are ignored

q)sum 1 2 3 0N
6

However, a sum across a general list will not display this behavior

q)sum (),/:1 2 3 0N
,0N

So, for your table situation, you might want to fill in with a zero beforehand

q)update d:sum 0^(a;b;c) from wn
a b c d
--------
  3 6 9
1 4 7 12
2 5 8 15

Or alternatively, make it s.t. you are actually summing across simple lists rather than general lists.

q)update d:sum each flip (a;b;c) from wn
a b c d
--------
  3 6 9
1 4 7 12
2 5 8 15

For a more complete reference on null treatment please see the reference website

Thomas Smyth - Treliant
  • 4,993
  • 6
  • 25
  • 36
JPC
  • 1,891
  • 13
  • 29
0

This is what worked:

select Answer:{[x;y;z;a] x+y+z+a }'[TypeA;TypeB;TypeC;TypeD] from 
([] dt:2014.01.01 2014.01.02 2014.01.03; TypeA:4 5 6; TypeB:1 2 3; TypeC:8 9 10; TypeD:3 4 5) 
stretchr
  • 615
  • 2
  • 9
  • 24