Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Summing digits of a number

Tags:

sql

presto

i'm using presto. I have an ID field which is numeric. I want a column that adds up the digits within the id. So if ID=1234, I want a column that outputs 10 i.e 1+2+3+4.

I could use substring to extract each digit and sum it but is there a function I can use or simpler way?

like image 756
Moosa Avatar asked Oct 04 '16 19:10

Moosa


People also ask

How do you sum numbers in SQL?

Example 1: Using SUM() with One Column In this query, we use SUM() alone in the SELECT statement. The SUM() function adds all values from the quantity column and returns the total as the result of the function. The name of the new result column (i.e. the alias) is sum_quantity .

How do you find the digit sum of a number?

What is digit sum? We can obtain the sum of digits by adding the digits of a number by ignoring the place values. So, for example, if we have the number 567 , we can calculate the digit sum as 5 + 6 + 7 , which will give us 18 .

How do I count the number of digits in SQL?

SQL Server LEN() Function The LEN() function returns the length of a string. Note: Trailing spaces at the end of the string is not included when calculating the length. However, leading spaces at the start of the string is included when calculating the length.


1 Answers

You can combine regexp_extract_all from @akuhn's answer with lambda support recently added to Presto. That way you don't need to unnest. The code would be really self explanatory if not the need for cast to and from varchar:

presto> select
    reduce(
        regexp_extract_all(cast(x as varchar), '\d'), -- split into digits array
        0, -- initial reduction element
        (s, x) -> s + cast(x as integer), -- reduction function
        s -> s -- finalization
    ) sum_of_digits
from (values 1234) t(x);

 sum_of_digits
---------------
            10
(1 row)
like image 172
Piotr Findeisen Avatar answered Sep 18 '22 20:09

Piotr Findeisen