2

Consider this table definition in SQL

CREATE TABLE matrices (
matrix text[][] NOT NULL
);

Assuming that every matrix in this table has the same dimensions, how to write a query to transpose them?

for example:

INSERT INTO matrices VALUES
(array[['1','2','3'],
       ['4','5','6']]),
(array[['f','e','d'],
       ['c','b','a']]);

after the transpose it should look like:

 {{1,4},{2,5},{3,6}}
 {{f,c},{e,b},{d,a}}
3
  • 1
    Please only tag the relevant RDBMS Commented Jun 2, 2020 at 9:21
  • Why the question is MySQL-tagged? Commented Jun 2, 2020 at 9:21
  • Unnest the array until separate elements storing their positional indices for each dimention then aggregate back in needed order. Commented Jun 2, 2020 at 9:25

1 Answer 1

1

An option uses generate_subscripts() to enumerate the indexes of each dimension of the array, and then two levels of aggregation.

We need a primary key column to properly rebuild each array - I assumed id (if you don't have such a column, we could generate it on the fly in a subquery with row_number()):

select id, array_agg(ar order by j) new_matrix
from (
    select m.id, j, array_agg(matrix[i][j] order by i) ar
    from matrices m
    cross join lateral generate_subscripts(m.matrix, 1) as s1(i)
    cross join lateral generate_subscripts(m.matrix, 2) as s2(j)
    group by m.id, j
) t
group by id

Demo on DB Fiddle

Sample data:

id | matrix           
-: | :----------------
 1 | {{1,2,3},{4,5,6}}
 2 | {{f,e,d},{c,b,a}}

Results:

id | new_matrix         
-: | :------------------
 1 | {{1,4},{2,5},{3,6}}
 2 | {{f,c},{e,b},{d,a}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.