当标签是字符串数组时,如何计算 SQL 中每个标签的项目数?
How do I count number of items per tag in SQL, when tags is an array of strings?
我有一个 table 看起来像这样:
ItemID, Tags
ItemID 是一个字符串,Tags 是一个字符串数组。
数据库引擎是 Presto:https://prestodb.io/docs/0.172/index.html
我必须 return 每个标签的 ItemID 计数,但我有点卡住了。我的第一个方法是提取标签并创建一个唯一列表,然后我希望通过一些连接魔法我能够 GROUP BY 然后计数。
我应该如何处理这个问题?我对 SQL 数组
没有太多经验
我也不知道如何使用 UNNEST 创建行,然后 table 从中得出:
SELECT filter(flatten(array_agg(split(tags, ','))), x -> x != '')
FROM my_items
这个 return 是一组独特的标签,显然使用 UNNEST 这可以变成一组行,但到目前为止我还没有运气将它转换成那个。尝试过类似的东西:
SELECT UNNEST(above subquery) FROM MY_ITEMS
我想你想要一个 unnest()
和聚合:
select t.tag, count(*)
from my_items i cross join
unnest(split(i.tags, ',')) t(tag)
group by t.tag;
不太确定,因为我无法在我的 Presto 上尝试(还)。但是 cardinality
功能可能会起作用。
cardinality(x) → bigint -- Returns the cardinality (size) of the array x.
来自此处的 Presto 文档 - https://prestodb.io/docs/current/functions/array.html
我有一个 table 看起来像这样:
ItemID, Tags
ItemID 是一个字符串,Tags 是一个字符串数组。
数据库引擎是 Presto:https://prestodb.io/docs/0.172/index.html
我必须 return 每个标签的 ItemID 计数,但我有点卡住了。我的第一个方法是提取标签并创建一个唯一列表,然后我希望通过一些连接魔法我能够 GROUP BY 然后计数。
我应该如何处理这个问题?我对 SQL 数组
没有太多经验我也不知道如何使用 UNNEST 创建行,然后 table 从中得出:
SELECT filter(flatten(array_agg(split(tags, ','))), x -> x != '')
FROM my_items
这个 return 是一组独特的标签,显然使用 UNNEST 这可以变成一组行,但到目前为止我还没有运气将它转换成那个。尝试过类似的东西:
SELECT UNNEST(above subquery) FROM MY_ITEMS
我想你想要一个 unnest()
和聚合:
select t.tag, count(*)
from my_items i cross join
unnest(split(i.tags, ',')) t(tag)
group by t.tag;
不太确定,因为我无法在我的 Presto 上尝试(还)。但是 cardinality
功能可能会起作用。
cardinality(x) → bigint -- Returns the cardinality (size) of the array x.
来自此处的 Presto 文档 - https://prestodb.io/docs/current/functions/array.html