sql查询计算奇数和偶数位数总和

时间:2014-12-08 07:55:26

标签: sql oracle

我需要一个SQL查询/函数,它会找出数字的SUM,它出现在偶数位置,数字的SUM存在于奇数位置。

示例:

如果数字为440065385

x=4+0+6+3+5=18(x is holding sum of odd positions)
y=4+0+5+8=17 (y holds the sum of even positions).

感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用数字表连接您的表格,将所有数字拆分成行,然后将赔率甚至位置数字分开。

with positions(position) as 
    (select level from dual connect by level <=25
    ),
digits as
    (
    select 
        t1.v,
        n.position ,
        cast(substr(t1.v ,length(t1.v) - n.position + 1, 1) as int) as digit
    from my_table t1 left join positions n
    on n.position <= length(t1.v)
    )
select
    v,
    sum(case when mod(position,2)=0 then digit else 0 end) as evensum,
    sum(case when mod(position,2)=1 then digit else 0 end) as oddsum
from
    digits
group by
    v

测试Sql Fiddle,结果:

V           EVENSUM ODDSUM
440065385   17      18

答案 1 :(得分:1)

您可以使用级别模拟迭代,并通过连接来实现相同的

with iterate as 
(select level as i from dual connect by level <=25)
 select
       table1.column1, 
       sum(decode(mod(iterate.i,2),0,substr(table1.column1,iterate.i,1))) sum_even,
       sum(decode(mod(iterate.i,2),1,substr(table1.column1,iterate.i,1))) sum_old
 from table1 ,iterate 
 where iterate.i <=length(table1.column1)
 group by table1.column1