[英]BigQuery / Count the number of rows until a specific row is reached
我在 BigQuery 中有數據。
我想在每個 ID 的“批准”事件之前計算“待定”事件的數量。
我將如何獲得每個個人 ID 的價值?
表事件
id event
1 pending
1 pending
1 pending
1 approved
2 pending
1 pending
1 pending
1 approved
2 approved
在這個例子中正確的結果是
id count_events
1 3
1 2
2 1
考慮以下方法
select id, countif(not flag) count_events
from (
select *, countif(flag) over(partition by id order by ts desc) grp
from (
select *,
if(lag(event) over(partition by id order by ts) = 'pending' and event = 'approved', true, false) flag
from your_table
)
)
group by id, grp
order by max(ts)
如果應用於您問題中的示例數據 - output 是
注意ts
的使用 - 你的表中必須有一些定義事件順序的列 - 通常它是時間戳,但可以是日期,或者只是序號等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.