Sql 对BigQuery数组类型执行循环和计算
我的原始数据B是INT64的数组: 我想计算B[n+1]-B[n]之间的差值,从而得到一个新的表,如下所示: 我发现我可以通过使用循环和IF条件以某种方式实现这一点:Sql 对BigQuery数组类型执行循环和计算,sql,google-bigquery,Sql,Google Bigquery,我的原始数据B是INT64的数组: 我想计算B[n+1]-B[n]之间的差值,从而得到一个新的表,如下所示: 我发现我可以通过使用循环和IF条件以某种方式实现这一点: DECLARE x INT64 DEFAULT 0; LOOP SET x = x + 1 IF(x < array_length(table.B)) THEN INSERT INTO newTable (SELECT A, B[OFFSET(x+1)] - B[OFFSET(x)]) from table EN
DECLARE x INT64 DEFAULT 0;
LOOP
SET x = x + 1
IF(x < array_length(table.B))
THEN INSERT INTO newTable (SELECT A, B[OFFSET(x+1)] - B[OFFSET(x)]) from table
END IF;
END LOOP;
有人能告诉我怎么做吗?或者有更好的方法来解决这个问题
谢谢。为此,您可以使用带有偏移量的unnest()
:
select id, a,
array_agg(b_el - prev_b_el order by n) as b_diffs
from (select t.*, b_el, lag(b_el) over (partition by t.id order by n) as prev_b_el
from t cross join
unnest(b) b_el with offset n
) t
where prev_b_el is not null
group by t.id, t.a
为此,可以将unnest()与偏移量一起使用
:
select id, a,
array_agg(b_el - prev_b_el order by n) as b_diffs
from (select t.*, b_el, lag(b_el) over (partition by t.id order by n) as prev_b_el
from t cross join
unnest(b) b_el with offset n
) t
where prev_b_el is not null
group by t.id, t.a
下面是实际工作-BigQuery
select * replace(
array(select diff from (
select offset, lead(el) over(order by offset) - el as diff
from unnest(B) el with offset
) where not diff is null
order by offset
) as B
)
from `project.dataset.table` t
如果要应用于问题中的样本数据,则输出为
以下内容实际有效-BigQuery
select * replace(
array(select diff from (
select offset, lead(el) over(order by offset) - el as diff
from unnest(B) el with offset
) where not diff is null
order by offset
) as B
)
from `project.dataset.table` t
如果要应用于问题中的样本数据,则输出为