BigQuery 父级和子级的平均值

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

我正在尝试获取子项目的平均数量。 我有一张如下表

parent_id| child_id | Type 
1        | 11         | A
1        | 11         | B
1        | 12         | A
1        | 12         | B
1        | 13         | A
2        | 14         | A
2        | 15         | B
2        | 15         | A

在输出中,我想知道对于给定的parent_id,A 的平均计数和B 的平均计数是多少。 我使用 groupby 实现了这一点。 但想检查在同一个查询中是否也可以获得 child_id 的 A 平均计数? 简而言之,获取每个子项的平均类型数,并添加一列,该列也会告诉我每个parent_id 的平均类型数。

sql google-bigquery
1个回答
0
投票

子总和作为规则,计算为条件总和,如

sum(case when type='A' then 1 else 0 end)type_A_qty

参见示例
创建表测试(parent_id int,child_id int,类型varchar(10)); 插入测试值 (1, 11, 'A') ,(1, 11, 'B') ,(1, 12, 'A') ,(1, 12, 'B') ,(1, 13, 'A') ,(2, 14, 'A') ,(2, 15, 'B') ,(2, 15, 'A') ;

select parent_id
  ,count(*) child_qty
  ,sum(case when type='A' then 1 else 0 end)type_A_qty
  ,sum(case when type='B' then 1 else 0 end)type_B_qty
  ,sum(case when type='A' or type='B' then 0 else 1 end)other_type_qty
from test
group by parent_id;

输出

parent_id 儿童数量 类型_A_数量 类型_B_数量 其他类型数量
1 5 3 2 0
2 3 2 1 0
© www.soinside.com 2019 - 2024. All rights reserved.