3
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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Here is an option if you are using Postgre 9.3 or later:

SELECT SUM(s.num::int) AS sum
FROM your_table t, unnest(string_to_array(replace(t.col::text, '|', '^'), '^')) s(num);

Demo

But the better long term fix would be to avoid such SQL olympics, and instead to normalize your data. Ideally each number you want to sum should be in a separate record, which is what the above query actually does to generate the sum.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.