There is barely enough information to make this work. But this does the job:
SELECT * FROM crosstab3(
$$
SELECT (rn/3)::text AS x, (rn%3)::text, item
FROM (
SELECT row_number() OVER () - 1 AS rn, trim(item) AS item
FROM (
SELECT CASE WHEN rn%2 = 1 THEN regexp_split_to_table(item, ',')
ELSE item END AS item
FROM (
SELECT row_number() OVER () AS rn, *
FROM regexp_split_to_table('Test 1|new york| X, Test 2| chicago|Y, Test 3| harrisburg, pa| Z', '\|') AS item
) x
) y
) z
$$)
Returns:
row_name | category_1 | category_2 | category_3
----------+------------+----------------+------------
0 | Test 1 | new york | X
1 | Test 2 | chicago | Y
2 | Test 3 | harrisburg, pa | Z
After splitting the string at |
, I build on the criterion that only lines with uneven row number shall be split at ,
.
I trim()
the results and add derivatives of another row_number()
to arrive at this intermediary state before doing the cross tabulation:
x | text | item
---+------+----------------
0 | 0 | Test 1
0 | 1 | new york
0 | 2 | X
1 | 0 | Test 2
1 | 1 | chicago
1 | 2 | Y
2 | 0 | Test 3
2 | 1 | harrisburg, pa
2 | 2 | Z
Finally, I apply the crosstab3()
function from the tablefunc
module. To install it, if you haven't already:
CREATE EXTENSION tablefunc;
Pre-process with regexp_replace()
Here is an alternative that may be easier to comprehend. Not sure which is faster. Complex regular expressions tend to be expensive:
SELECT trim(split_part(a,'|', 1)) AS column1
,trim(split_part(a,'|', 2)) AS column2
,trim(split_part(a,'|', 3)) AS column3
FROM (
SELECT unnest(
string_to_array(
regexp_replace('Test 1|new york| X, Test 2| chicago|Y, Test 3| harrisburg, pa| Z'
,'([^|]*\|[^|]*\|[^,]*),', '\1~^~', 'g'), '~^~')) AS a
) sub
This one replaces commas (,
) only after two pipes (|
), before proceeding.
Now using *
instead of +
to allow for empty strings between the pipes.