如何计算 Bigquery 中指定非空行之前的空行数

问题描述 投票:0回答:1

我的数据如下:

我打算创建一个 BQ 查询,计算每个 id 在指定日期之前的“空”月数(在本示例中,所有 ID 的指定日期为 2023 年 8 月 1 日;但我稍后希望这样做这适用于每个 ID 的日期不同的情况,因此如果您有建议可以解释这一点,我将不胜感激)

期望的输出是这样的: 例如2023 年 8 月 1 日之前,ID 111 有 3 个无效月份,222 有 5 个无效月份等

尝试检查这些,但数据似乎没有以相同的方式格式化

我认为我得到的最接近的是这个 - 但所需的输出并不完全是我所需要的(例如,我无法选择提及我想要计算前面的空行的确切日期)

google-bigquery count null
1个回答
0
投票

需要几个CTE。

tbl
是示例的原始数据。
helper
计算未来发生于此
null
id
条目,并在
count_na
列中给出该值。
helper
count_na
中查找
nr
中的下一个非空项。接下来,对这些值进行减法。

您只想显示具有非空

nr
的行。
qualify
子句仅过滤最新条目。

请注释掉最后两行过滤器。另请查询每个 CTE 以更好地理解。

With tbl as (
 Select *, case row_number() over (order by id, month) when 3 then 132 when 4 then 89 when 8 then 300 when 10 then 114 when 16 then 334 end as nr
 from unnest(['111','222'])as id, unnest(generate_date_array(date "2023-01-01",date "2023-08-01",interval 1 month)) as month 

)
, helper as  (
Select *,
countif(nr is null) over fill count_na
 from tbl
window fill as (partition by id order by month desc rows between unbounded preceding and 0 preceding) 
order by 1,2
), helper2 as
(
Select *,
last_value(if(nr is null,null,count_na) ignore nulls) over fill as last_count
 from helper
window fill as (partition by id order by month desc rows between unbounded preceding and 1 preceding) 
order by 1,2
)

Select *,
count_na - last_count as nr_null_months
from helper2
where nr is not null and last_count is not null # comment this out
qualify month=max(month) over (partition by id) # comment this out
order by 1,2
© www.soinside.com 2019 - 2024. All rights reserved.