【发布时间】:2020-05-15 00:09:10
【问题描述】:
我对 SQL 和 bigquery 还很陌生,并且正在使用大约 140 万行的数据集。
我目前感兴趣的值是 category_name(字符串)、item_id(字符串)。我感兴趣的是计算 category_name 中每个值的不同 item_id(此列共有 269 个不同值)。基本上在我的基础数据集中,每一行数据都包含一个 item_id 的实例,它显示在一个 category_name 中,其中 item_id 可以根据当天出现的 category_names 的数量每天有多行。
我已经能够运行一个成功的查询,为 category_name 的每个值添加不同 item_id 的新列,现在最终输出应该是我无法弄清楚如何计算不同 item_id 的百分比对于 1 个类别名称,它也出现在每个其他类别名称中。所以基本上我正在寻找一个新列(如数据透视表),它将计算 2 个 category_names 的匹配 item_ids,然后将该计数除以 1 个 category_name 中的不同 item_id 的总数。因此,基本上每个 category_name 将有 269 个新列,并且每一行将表示基本 category_name 与每个其他 category_name 的重叠百分比。
这是我当前感兴趣的表格中的数据
category_name | item_id
---------------|------------
category1 | item1
category2 | item1
category3 | item1
category1 | item2
category4 | item2
category1 | item3
category5 | item3
category5 | item2
category6 | item4
category3 | item5
category3 | item6
category1 | item6
category2 | item5
category1 | item4
这是我当前的查询结果的样子
category_name | distinct_items
---------------|-----------------
category1 | 5
category2 | 2
category3 | 3
category4 | 1
category5 | 2
category6 | 1
这是我希望最终输出的样子:
category_name | category1 | category2 | category3 | category4 | category5 | category6
--------------------------------------------------------------------------------------------------------
category1 | 100% | 20% | 40% | 20% | 40% | 20%
category2 | 50% | 100% | 100% | 0% | 0% | 0%
category3 | 66.67% | 66.67% | 100% | 0% | 0% | 0%
category4 | 100% | 0% | 0% | 100% | 100% | 0%
category5 | 100% | 0% | 0% | 50% | 100% | 0%
category6 | 100% | 0% | 0% | 0% | 0% | 100%
本质上,category_name 的行值将是 category_name 是目标并将它们的 distinct_items 总数与其他 category_names 进行比较,并根据 item_ids 查找匹配百分比/distinct_items 总数。如果有另一种方法可以在没有数据透视表的情况下获得此输出,那也将不胜感激。上下文有 269 个 category_names 和 6525 个不同的 item_ids。
如果有一个更简单的公式,我可以在谷歌数据工作室中使用这个聚合,因为数据工作室的最终输出应该是散点图,x 和 y 轴类别名称和气泡是重叠百分比所以本质上只是用散点图可视化数据透视表结果。如果我的描述和问题中的任何内容没有意义或需要更清晰,请随时标记我并让我知道什么是令人困惑的。任何帮助是极大的赞赏!谢谢
【问题讨论】:
标签: sql google-bigquery pivot-table google-data-studio