Search code examples
postgresqlpostgresql-9.1postgresql-9.3

Sum all odd digits in a number in PostgreSQL


Is there a built in function in PostgreSQL to sum the alternate digits starting from right hand side?

Input: 890400021003
Output:
3 + 0 + 2 + 0 + 4 + 9 = 18 
0 + 1 + 0 + 0 + 0 + 8 = 9 

Basically I want to print each alternate numbers and sum it up as above, please advice for any solution in Postgres


Solution

  • In Postres 9.4, you can do this easily with a string, using string_to_array() and unnest() with ordinality:

    select ord % 2, sum(val::numeric)
    from (select reverse('890400021003'::text) as x) x, lateral
         unnest(string_to_array(x, NULL)) with ordinality u(val, ord)
    group by ord % 2;
    

    In 9.3 you can do this with a lateral join:

    select i % 2, sum(substring(x.x, g.i, 1)::numeric)
    from (select reverse('890400021003'::text) as x) x, lateral
         generate_series(1, length(x.x)) g(i)
    group by i % 2;
    

    And you can apply the same idea using a subquery in earlier versions.