在BigQuery中连续从前一行减去

huangapple go评论72阅读模式
英文:

Continuous subtraction from previous row in Bigquery

问题

我需要知道是否有一种方法可以实现连续的减法,就像这样:

从可用列中取第一个值,然后不断减去一个常数值(这里是10),以获得所需的列。

可用 所需
100 90
100 80
100 70

我已经使用行号作为计数器来进行减法,但有一个问题,当所需列变为0时,计数器需要重新开始。(如果我使用行号)

可用 计数器 所需
100 1 100 - (1 * 10) = 90
100 2 100 - (2 * 10) = 80

在BigQuery中是否有一种方法实现这种连续减法?

英文:

I need to know if there is a way I can achieve a continuous subtraction like:

Where take first value of available column and keep on subtracting a constant value (10 here) to get the required column.

Availabl Required
100 90
100 80
100 70

I have used row number as a counter to subtract the number but there is a problem as when the Required becomes 0, counter needs to restart. (If I used row number)

Available Counter Required
100 1 100-(1*10) = 90
100 2 100-(2*10) =80

Is there a method for this continuous subtraction in bigquery?

答案1

得分: 1

考虑以下(BigQuery标准SQL)。这可能是您的用例的良好起点

select Available, Counter, Required 
from (
  select *, 
    row_number() over(partition by div(pos, 1 + cast(Available/10 as int))) as Counter,
    Available - 10 * row_number() over(partition by div(pos, 1 + cast(Available/10 as int))) as Required 
  from (
    select *, row_number() over() as pos
    from your_table
  )
)  

如果应用于您示例中的样本数据 - 输出是:

在BigQuery中连续从前一行减去

英文:

Consider below (BigQuery Standard SQL). Could be good start for your use case

select Available, Counter, Required 
from (
  select *, 
    row_number() over(partition by div(pos, 1 + cast(Available/10 as int))) as Counter,
    Available - 10 * row_number() over(partition by div(pos, 1 + cast(Available/10 as int))) as Required 
  from (
    select *, row_number() over() as pos
    from your_table
  )
)    

if applied to sample data in your example - output is

在BigQuery中连续从前一行减去

huangapple
  • 本文由 发表于 2023年7月10日 14:16:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76651086.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定