Summing parts of a column
yaronkoral
Community Edition User ✭
I have a column which stores multiple vertical bar separated values.
For example:
40|30|20
70
100|20|1|1|1|10
I would like to get a sum of all parts of the string:
90
70
133
Is there a way to do it in Vertica?
0
Answers
@yaronkoral : Please find the solution below. You need to use another column from your table to sum up the results of a column of a particular row
dbadmin=> select * from test_f;
a | b
-----------------+---
40|30|20 | 1
70 | 2
100|20|1|1|1|10 | 3
(3 rows)
dbadmin=> select b, sum(a) from (SELECT b,v_txtindex.stringTokenizerDelim(a, '|') OVER(partition by b order by b) as a FROM test_f order by 1,2) g group by 1;
b | sum
---+-----
1 | 90
2 | 70
3 | 133
(3 rows)
dbadmin=>
Thank you @SruthiA, works perfectly!
@yaronkoral - Just for fun, here is another route via a User Defined SQL Function:
If you have to handle more that 10 values to sum, you'd have to add more SPLIT_PART calls
Or yet another two:
a) convert to array and explode:
b) CROSS JOIN with an in-line index table ...