BigQuery 关注更多领域
Posted
技术标签:
【中文标题】BigQuery 关注更多领域【英文标题】:BigQuery pivot on more fields 【发布时间】:2021-11-02 04:32:14 【问题描述】:跟进Pivot table data using GROUP BY ROLLUP,我想按照米哈伊尔在 3x3 数据透视表上显示的线条生成一个数据透视。在 Excel 中,它为我们提供了 180 个值单元格:
它给出了 128 个非空单元格,但包括空单元格在内的 180 个单元格(右下角是计数:128,左上角是 15Rx12C=180)。这是我现在的查询,它给了我 128 个“值单元格”:
select
(case when grp_set & 1 > 0 then Reseller end) as Reseller,
(case when grp_set & 2 > 0 then ProductGroup end) as ProductGroup,
(case when grp_set & 4 > 0 then Product end) as Product,
(case when grp_set & 8 > 0 then Year end) as Year,
(case when grp_set & 16 > 0 then Quarter end) as Quarter,
(case when grp_set & 32 > 0 then Product_Info end) as Product_Info,
sum(Revenue) as Revenue,
sum(Units) as Units
from `first-outlet-750.biengine_tutorial.Product`, unnest(generate_array(1, 64)) grp_set
where Year IN (2020) and Quarter in ('Q1', 'Q2')
group by 1, 2, 3, 4, 5, 6
having not (Quarter is null and Product_Info is not null)
and not (Year is null and Quarter is not null)
and not (Reseller is null and ProductGroup is not null)
and not (ProductGroup is null and Product is not null)
order by 1, 2, 3, 4 , 5, 6
我将如何调整此查询使其返回 180 个单元格结果(即 90 行)而不是 128 个(64 行)?
【问题讨论】:
【参考方案1】:试试下面
select
(case when grp_set & 1 > 0 then Reseller end) as Reseller,
(case when grp_set & 2 > 0 then ProductGroup end) as ProductGroup,
(case when grp_set & 4 > 0 then Product end) as Product,
(case when grp_set & 8 > 0 then Year end) as Year,
(case when grp_set & 16 > 0 then Quarter end) as Quarter,
(case when grp_set & 32 > 0 then Product_Info end) as Product_Info,
sum(Revenue) as Revenue,
sum(Units) as Units
from `first-outlet-750.biengine_tutorial.Product`, unnest(generate_array(1, 64)) grp_set
where Year IN (2020) and Quarter in ('Q1', 'Q2')
group by 1, 2, 3, 4, 5, 6
having not (Quarter is null and Product_Info is not null)
and not (Year is null and Quarter is not null)
and not (ProductGroup is null and Product is not null)
order by 1, 2, 3, 4 , 5, 6
【讨论】:
这给了我们 360 个结果(180 行)而不是 180 个单元格。我添加了一些not (Reseller is null and ProductGroup is not null)...
's。
哎呀,误读了这个。再看……
查看正确答案
这里的想法是只对自然相关的维度使用“过滤器”——比如季度必须有一个年份;产品必须有一个ProductGroup;在您的示例中看起来 ProductInfo 取决于 Quarter;所以应该删除的是 Reseller 和 ProductGroup - 这里没有任何自然依赖 - 希望它有意义 :o)
太棒了。刚刚问了另一个关于将其变成表格函数的可行性的问题。以上是关于BigQuery 关注更多领域的主要内容,如果未能解决你的问题,请参考以下文章