如何使用 SQL (BigQuery) 将一串数字相加?
How to add up a string of numbers using SQL (BigQuery)?
我有这样一串数字:
670000000000100000000000000000000000000000000000000000000000000
我想把上面例子中的这些数字相加得到 14:6+7+0+...+1+0+...+0+0+0=14
我如何在 BigQuery 中执行此操作?
考虑以下方法
with example as (
select '670000000000100000000000000000000000000000000000000000000000000' as s
)
select s, (select sum(cast(num as int64)) from unnest(split(s,'')) num) result
from example
有输出
又一个[有趣]选项
create temp function sum_digits(expression string)
returns int64
language js as """
return eval(expression);
""";
with example as (
select '670000000000100000000000000000000000000000000000000000000000000' as s
)
select s, sum_digits(regexp_replace(replace(s, '0', ''), r'(\d)', r'+')) result
from example
有输出
它的作用是-
- 首先它将初始的长字符串转换为较短的字符串 -
671
.
- 然后将其转换为表达式 -
+6+7+1
- 最后传递给javascript
eval
函数(不幸的是BigQuery没有[希望如此]eval
函数)
我有这样一串数字:
670000000000100000000000000000000000000000000000000000000000000
我想把上面例子中的这些数字相加得到 14:6+7+0+...+1+0+...+0+0+0=14
我如何在 BigQuery 中执行此操作?
考虑以下方法
with example as (
select '670000000000100000000000000000000000000000000000000000000000000' as s
)
select s, (select sum(cast(num as int64)) from unnest(split(s,'')) num) result
from example
有输出
又一个[有趣]选项
create temp function sum_digits(expression string)
returns int64
language js as """
return eval(expression);
""";
with example as (
select '670000000000100000000000000000000000000000000000000000000000000' as s
)
select s, sum_digits(regexp_replace(replace(s, '0', ''), r'(\d)', r'+')) result
from example
有输出
它的作用是-
- 首先它将初始的长字符串转换为较短的字符串 -
671
. - 然后将其转换为表达式 -
+6+7+1
- 最后传递给javascript
eval
函数(不幸的是BigQuery没有[希望如此]eval
函数)