[英]how to split rows into multiple rows based on values in an array column in postgresql? (see example in description)
ia have postgresql query that gets results like this: ia 有 postgresql 查询,得到如下结果:
id | arrayElements
0 | [0, 2, 1]
1 | [0, 3]
2 | [1]
In the above example the values inside arrayElements
means something.在上面的示例中, arrayElements
中的值意味着什么。 I want to split this table based on those arrayElements (to get count).我想根据这些 arrayElements 拆分此表(以获取计数)。
I want to convert it to:我想将其转换为:
id | arrayElement
0 | 0
0 | 2
0 | 1
1 | 0
1 | 3
2 | 1
here i'm essentially spliting rows by elements inside arrayElements
column.在这里,我实际上是按arrayElements
列中的元素拆分行。 arrayElements
column contains string data. arrayElements
列包含字符串数据。
i am using postgresql 14.我正在使用 postgresql 14。
my end goal is to get the count per arrayElement which is why i'm separating them into different rows.我的最终目标是获得每个 arrayElement 的计数,这就是我将它们分成不同行的原因。
how should I solve this?我应该如何解决这个问题?
Also, if you want to get count of arrayElements
, you can do this:此外,如果您想获取arrayElements
的计数,您可以这样做:
select sum(cardinality(arrayElements)) from tableName;
select id, UNNEST(string_to_array(arrayElements, ',') as arrayElement;
should do it.应该这样做。 In my case arrayElement
was a string that I had to convert to an array.在我的例子中, arrayElement
是一个字符串,我必须将其转换为数组。
There may be the case that elements might have a '[' or ']' at the beginning or end so to fix that you can modify the query to use SUBSTRING and remove those square brackets:可能存在元素在开头或结尾可能有“[”或“]”的情况,因此您可以修改查询以使用 SUBSTRING 并删除这些方括号:
SELECT
SUBSTRING(UNNEST(string_to_array(arrayElements, ',')), '([0-9]{1,10})') AS "arrayElement",
COUNT(id)
FROM table
GROUP BY arrayElement
the regex used in substring assumes that the maximum number of digits arrayElement can have is 10. substring 中使用的正则表达式假定 arrayElement 可以拥有的最大位数为 10。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.