如何计算 bigquery 数组字段中元素的频率
Posted
技术标签:
【中文标题】如何计算 bigquery 数组字段中元素的频率【英文标题】:How to count frequency of elements in a bigquery array field 【发布时间】:2018-01-23 21:44:39 【问题描述】:我有一张如下所示的表格:
我正在寻找一个表格,它给出了l_0, l_1, l_2, l_3
字段中元素的频率计数。
例如,输出应如下所示:
| author_id | year | l_o.name | l_0.count| l1.name | l1.count | l2.name | l2.count| l3.name | l3.count|
| 2164089123 | 1987 | biology | 3 | botany | 3 | | | | |
| 2595831531 | 1987 | computer science | 2 | simulation | 2 | computer simulation | 2 | mathematical model | 2 |
编辑:
在某些情况下,数组字段可能包含不止一种类型的元素。例如l_0
可以是['biology', 'biology', 'geometry', 'geometry']
。在这种情况下,字段l_0, l_1, l_2, l_3
的输出将是一个嵌套重复字段,其中包含l_0.name
中的所有元素以及l_0.count
中的所有相应计数。
【问题讨论】:
目前还不清楚每个重复字段的具体内容是什么!每个字段总是相同的元素还是可以是多个?如果是多个 - 结果应该是什么样子? 每个字段的元素并不总是相同。对于多个元素,对象的计数应该是具有元素名称和元素计数的重复嵌套对象。 【参考方案1】:这应该可以工作,假设您想基于每个数组计算:
SELECT
author_id,
year,
(SELECT AS STRUCT ANY_VALUE(l_0) AS name, COUNT(*) AS count
FROM UNNEST(l_0) AS l_0) AS l_0,
(SELECT AS STRUCT ANY_VALUE(l_1) AS name, COUNT(*) AS count
FROM UNNEST(l_1) AS l_1) AS l_1,
(SELECT AS STRUCT ANY_VALUE(l_2) AS name, COUNT(*) AS count
FROM UNNEST(l_2) AS l_2) AS l_2,
(SELECT AS STRUCT ANY_VALUE(l_3) AS name, COUNT(*) AS count
FROM UNNEST(l_3) AS l_3) AS l_3
FROM YourTable;
为避免如此多的重复,您可以使用 SQL UDF:
CREATE TEMP FUNCTION GetNameAndCount(elements ARRAY<STRING>) AS (
(SELECT AS STRUCT ANY_VALUE(elem) AS name, COUNT(*) AS count
FROM UNNEST(elements) AS elem)
);
SELECT
author_id,
year,
GetNameAndCount(l_0) AS l_0,
GetNameAndCount(l_1) AS l_1,
GetNameAndCount(l_2) AS l_2,
GetNameAndCount(l_3) AS l_3
FROM YourTable;
如果您可能需要考虑一个数组中的多个不同名称,您可以让 UDF 返回一个包含相关计数的数组:
CREATE TEMP FUNCTION GetNamesAndCounts(elements ARRAY<STRING>) AS (
ARRAY(
SELECT AS STRUCT elem AS name, COUNT(*) AS count
FROM UNNEST(elements) AS elem
GROUP BY elem
ORDER BY count
)
);
SELECT
author_id,
year,
GetNamesAndCounts(l_0) AS l_0,
GetNamesAndCounts(l_1) AS l_1,
GetNamesAndCounts(l_2) AS l_2,
GetNamesAndCounts(l_3) AS l_3
FROM YourTable;
请注意,如果您想跨行执行计数,则需要取消嵌套数组并在外层执行GROUP BY
,但根据问题,这看起来不是您的意图.
【讨论】:
我正在寻找的实际解决方案完全由您提供的最后一个解决方案完成。我也在稍后的编辑中澄清了我的问题。非常感谢!以上是关于如何计算 bigquery 数组字段中元素的频率的主要内容,如果未能解决你的问题,请参考以下文章