Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate sum of numbers in a string in postgresql

1^1^1^5^1|1^1|1^1

Is there a simple way to add all above numbers in postgresql. I would like to write a function that takes above string and outputs 13.

like image 705
Aseem Avatar asked Dec 20 '25 12:12

Aseem


1 Answers

You could use the function regexp_split_to_table

SELECT sum(s::int) 
  FROM regexp_split_to_table('1^1^1^5^1|1^1|1^1','\D') as s

Here you use the regex \D to split on everything that is not a digit, leaving you with the groups of digits (read more about postgres regex), which you then sum as integers.

like image 179
Jasen Avatar answered Dec 22 '25 13:12

Jasen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!