2017-07-02 69 views
0

PostgreSQL中是否有一个内置函数来总结从右侧开始的另一位数字?PostgreSQL中一个数字中的所有奇数位数总和

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

基本上我要打印的每张备用号码并如上概括起来,请指教在Postgres的任何解决方案

+1

为什么你想在db中这样做,而不是在应用程序中计算它? – user1937198

+0

因为我想对卡号 –

回答

2

在Postres 9.4,你可以用一个字符串做到这一点很容易,使用string_to_array()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; 

在9.3你可以用一个横向做加盟:

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; 

您可以在早期版本中使用子查询应用相同的想法。

+0

'(length(x) - ord)%2'随机使用一个数的模10算法来满足“从右手边开始” – Abelisto

+0

@Abelisto的要求。 。 。接得好。我选择了只是扭转字符串。 –

+0

@Gordon感谢您的解决方案,我正在检查它。我在x86_64-pc-linux-gnu上使用PostgreSQL 9.5.2,由gcc(GCC)编译4.8.2 20140120(Red Hat 4.8.2-16),64位版本 –

相关问题