Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unnest row in PostgreSQL and include count of unnesting occurences

Following on from Matt’s answer in: Split column into multiple rows in Postgres

I want to unnest a row into multiple rows based on a character in a cell, however I also want to include a count column containing the number of times a row was unnested.

I want this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

       name            |  id
-----------------------+------
 alpha, bravo, charlie |    1
 yankee, xray          |    2
 hotel                 |    3 
 indigo                |    4

to become this:

       name            |  id  | count
-----------------------+------+-------
 alpha                 |    1 |   3
 bravo                 |    1 |   3
 charlie               |    1 |   3
 yankee                |    2 |   2
 xray                  |    2 |   2
 hotel                 |    3 |   1
 indigo                |    4 |   1

The initial unnest query would be:

SELECT unnest(string_to_array(name, ', ')) as name, id
FROM table

>Solution :

You can use a cross join with regex:

select k, t.id, cardinality(regexp_split_to_array(t.name, ', ')) 
from tbl t cross join regexp_split_to_table(t.name, ', ') k

See fiddle.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading