在没有 NULL 或重复值的窗口上滚动计数

the*_*may 1 google-bigquery

id考虑已按时间戳分组并按降序排序的关注窗口。

ID 时间戳 瓦尔
10:50 无效的
10:40 A
10:30 A
10:20 无效的
10:10 无效的
10:00
9:50 C
9:40 无效的
9:30 d
9:20 无效的

假设val一旦出现不同的值,a就不会再次出现。也就是说,我不会出现,a,b,aa,null,a可能会出现。我想针对valNULL见过或以前见过的条件生成滚动计数。也就是说,我想要这样的东西:

ID 时间戳 瓦尔 数数
10:50 无效的 0
10:40 A 1
10:30 A 1
10:20 无效的 1
10:10 A 1
10:00 2
9:50 C 3
9:40 无效的 3
9:30 d 4
9:20 无效的 4

所以本质上是一个“崩溃”的计数。我尝试过类似的东西

SELECT *, COUNT(val) OVER (PARTITION BY id ORDER BY timestamp DESC) count
Run Code Online (Sandbox Code Playgroud)

但这并没有忽视val之前发生的事情。

知道如何做到这一点吗?

Mik*_*ant 5

考虑以下方法

select * except(first_seen),
  countif(first_seen and not val is null) over(order by timestamp desc) distinct_count
from (
  select *, 
    1 = row_number() over(partition by val order by timestamp desc) first_seen
  from table
)    
Run Code Online (Sandbox Code Playgroud)

如果应用于您问题中的样本数据 - 输出是

在此输入图像描述