简体   繁体   中英

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:

id | arrayElements
 0 | [0, 2, 1]
 1 | [0, 3]
 2 | [1]

In the above example the values inside arrayElements means something. I want to split this table based on those arrayElements (to get count).

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 column contains string data.

i am using postgresql 14.

my end goal is to get the count per arrayElement which is why i'm separating them into different rows.

how should I solve this?

Also, if you want to get count of arrayElements , you can do this:

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM