I have a table:
CREATE TABLE p (
id text PRIMARY KEY,
t text[],
r int[]
);
Columns t
and r
are multi-dimensional, where the number of elements in each sub-array for a given row is different.
id | t | r |
---|---|---|
p1 | {{"a",NULL,NULL},{"b","c","d"},{"b",NULL,NULL}} | {{1,NULL,NULL},{1,1,2},{1,NULL,NULL}} |
p2 | {{"a",NULL},{"b","c"},{"b",NULL}} | {{1,NULL},{1,1},{1,NULL}} |
I want to unnest the data in the columns and have a subscript value describing the sub-array that the row came from (this is wrong):
select p.id, u.stage, u.t, u.r
from p,
unnest(t, r) with ordinality as u(t, r, stage);
This gives the row from the unnest, i.e.:
id | stage | r | t |
---|---|---|---|
"p1" | 1 | "a" | 1 |
"p1" | 2 | ||
"p1" | 3 | ||
"p1" | 4 | "b" | 1 |
"p1" | 5 | "c" | 1 |
"p1" | 6 | "d" | 2 |
"p1" | 7 | "b" | 1 |
"p1" | 8 | ||
"p1" | 9 | ||
"p2" | 1 | "a" | 1 |
"p2" | 2 | ||
"p2" | 3 | "b" | 1 |
"p2" | 4 | "c" | 1 |
"p2" | 5 | "b" | 1 |
"p2" | 6 |
What I want is to get an subscript describing from which sub-array the data came from, like this:
id | stage | r | t |
---|---|---|---|
"p1" | 1 | "a" | 1 |
"p1" | 1 | ||
"p1" | 1 | ||
"p1" | 2 | "b" | 1 |
"p1" | 2 | "c" | 1 |
"p1" | 2 | "d" | 2 |
"p1" | 3 | "b" | 1 |
"p1" | 3 | ||
"p1" | 3 | ||
"p2" | 1 | "a" | 1 |
"p2" | 1 | ||
"p2" | 2 | "b" | 1 |
"p2" | 2 | "c" | 1 |
"p2" | 3 | "b" | 1 |
"p2" | 3 |
How do I do this please? I don't know how many array elements will be in t
and r
, but both arrays will have the same dimensions in the same row.