Skip to content
Advertisement

How to get increment number when there are any change in a column in Bigquery?

I have data date, id, and flag on this table. How I can get the value column where this column is incremental number and reset from 1 when there are any change in flag column?

my table

Advertisement

Answer

Consider below approach

select * except(changed, grp),
  row_number() over(partition by id, grp order by date) value
from (
select *, countif(changed) over(partition by id order by date) grp
from (
  select *,
    ifnull(flag != lag(flag) over(partition by id order by date), true) changed
  from `project.dataset.table`
))     

if applied to sample data in your question – output is

enter image description here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement