-4
我需要一個SQL查詢/函數,它將找出數位的總和,它出現在偶數位置和數字的總和位於奇數位置。SQL查詢來計算奇數和偶數的位數總和
實施例:
如果號碼是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).
感謝。
我需要一個SQL查詢/函數,它將找出數位的總和,它出現在偶數位置和數字的總和位於奇數位置。SQL查詢來計算奇數和偶數的位數總和
實施例:
如果號碼是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).
感謝。
可以使用水平模仿迭代並連接通過以達到相同的
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
你可以用數字表加入你的表格,將所有數字拆分成若干行,然後分別計算賠率和位置數字。
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
爲什麼會有人要編這個使用SQL? : - | – Smutje 2014-12-08 07:56:18
不要將SQL用於沒有設計的事情。這只是錯誤的而不是表現! – 2014-12-08 07:58:31
固定的位數是多少?什麼是列的數據類型? – 2014-12-08 07:59:09