
今日は
select '{ {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 0, 1, 2} }' :: int[]; +---------------------------------+ | int4 | +---------------------------------+ | {{1,2,3,4},{5,6,7,8},{9,0,1,2}} | +---------------------------------+ (1 row)
↓ 完成形のクエリ。上の
with a (mat ) as ( select '{ {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 0, 1, 2} }' :: int[]-- albitary matrix ) select i, array_agg(val order by j) from a, unnest(mat ) with ordinality as x(val, j) , cast((j - 1) / array_length(mat , 2) as int) as i group by i; +---+-----------+ | i | array_agg | +---+-----------+ | 0 | {1,2,3,4} | | 1 | {5,6,7,8} | | 2 | {9,0,1,2} | +---+-----------+ (3 rows)

以下、段階的な説明です。最初に
with a (mat) as ( select '{ {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 0, 1, 2} }' :: int[] ) select val, j from a, unnest(mat)with ordinality as x(val, j); +-----+----+ | val | j | +-----+----+ | 1 | 1 | | 2 | 2 | | 3 | 3 | | 4 | 4 | | 5 | 5 | | 6 | 6 | | 7 | 7 | | 8 | 8 | | 9 | 9 | | 0 | 10 | | 1 | 11 | | 2 | 12 | +-----+----+ (12 rows)
↓
with a (mat) as ( select '{ {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 0, 1, 2} }' :: int[] ) select i, j, val from a, unnest(mat) with ordinality as x(val, j) , cast((j - 1) / array_length(mat, 2) as int) as i; +---+----+-----+ | i | j | val | +---+----+-----+ | 0 | 1 | 1 | | 0 | 2 | 2 | | 0 | 3 | 3 | | 0 | 4 | 4 | | 1 | 5 | 5 | | 1 | 6 | 6 | | 1 | 7 | 7 | | 1 | 8 | 8 | | 2 | 9 | 9 | | 2 | 10 | 0 | | 2 | 11 | 1 | | 2 | 12 | 2 | +---+----+-----+ (12 rows)
後は行番号
with a (mat) as ( select '{ {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 0, 1, 2} }' :: int[]-- albitary matrix ) select i,array_agg(val order by j) from a, unnest(mat) with ordinality as x(val, j) , cast((j - 1) / array_length(mat, 2) as int) as igroup by i ; +---+-----------+ | i | array_agg | +---+-----------+ | 0 | {1,2,3,4} | | 1 | {5,6,7,8} | | 2 | {9,0,1,2} | +---+-----------+ (3 rows)
2
with a (ary) as ( values ( '{1, 2, 3, 4}' :: int[] ), ( '{5, 6, 7, 8}' ), ( '{9, 0, 1, 2}' ) ) select array_agg(ary) from a; +---------------------------------+ | array_agg | +---------------------------------+ | {{1,2,3,4},{5,6,7,8},{9,0,1,2}} | +---------------------------------+ (1 row)

↓
with a (ary) as ( values ( '{1, 2, 3, 4}' :: int[] ), ( '{5, 6, 7, 8}' ), ( '{9, 0, 1, 2}' ) ) select array_agg(aryorder by ary desc ) from a; +---------------------------------+ | array_agg | +---------------------------------+ | {{9,0,1,2},{5,6,7,8},{1,2,3,4}} | +---------------------------------+ (1 row)

もう少しサイズの大きい