Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add up a string of numbers using SQL (BigQuery)?

I have a string of numbers like this:

670000000000100000000000000000000000000000000000000000000000000

I want to add up these numbers which in the above example would result in 14: 6+7+0+...+1+0+...+0+0+0=14

How would I do this in BigQuery?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using a UDF:

CREATE TEMP FUNCTION sum_string(data STRING)
RETURNS INT64
LANGUAGE js AS """
  return data.split('').reduce((acc, i) => acc + parseInt(i), 0);
""";

WITH example AS (
  SELECT '670000000000100000000000000000000000000000000000000000000000000' AS s
)
SELECT *, sum_string(s)
FROM example;

returns

s                                                               f0_
670000000000100000000000000000000000000000000000000000000000000 14

This will fail if your string contains non-digit characters though, you might want to some checks/error-handling if that can happen.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading