简体   繁体   中英

BigQuery: counts iterations per work block

I need a query in BIGQUERY that can count the number of iterations per work block.

When it gets to 'done', a block of work will be finished.

I have this table:

version_id      status
ghfjghj         pending
gsffsg          pending
jhkukiul        done
fsgsfgffgsf     pending
nmyumuju        done

and I want this result:

block   iterations
   1            3
   2            2

You can calculate the number of statuses it takes to reach every new done status. It works if you have PK, or some unique ID column. Sample data:

with cte  as (
  select 1 as id,'pending' as status
  union all select 2,'pending'
  union all select 3, 'done'
  union all select 4,'pending'
  union all select 5, 'done'
) 

Enumerating each Done status (block) and all statuses (rn).

,
cte2 as (
  select 
    row_number () over (partition by status order by id) as block,
    row_number () over (order by id) as rn,
  id,status
  from cte)

Calculating the index difference between this and previous Done status, for each Done status to find the number of other statuses till done, which appears to be iteration number.

select 
  block,
  rn-lag(rn,1,0) over (order by block) as iteration
  from cte2
  where status = 'done'
  order by 1

fiddle The fiddle is for T-SQL, but works for Bigquery SQL too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM