我需要从值列表中创建一个二维数组。 E. g。我们有一个表有一个名为'Number'的字段,其中有15个记录,从1到15。
SELECT array_agg(Number) from someTable;
array_agg
-------------------------------------
{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
(1 row)
如何使用SELECT语句聚合它们以获得具有固定宽度(例如,4)和无限高度的二维数组?
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15}
}
感谢。
答案 0 :(得分:1)
作为实际多维数组的变通方法:
以4作为固定宽度,将它们聚为4:
组SELECT ARRAY_AGG(g)
FROM (
SELECT g, ROW_NUMBER() OVER() - 1 AS r
FROM generate_series(1, 15) g
) x
GROUP BY r / 4
如果你想因为某种原因想要把所有这些结合起来,那么你也可以这样做:
SELECT ARRAY_AGG(a::TEXT)
FROM (
SELECT ARRAY_AGG(g) AS a
FROM (
SELECT g, ROW_NUMBER() OVER() - 1 AS r
FROM generate_series(1, 15) g
) x
GROUP BY r / 4
) y
结果:{"{1,2,3,4}","{5,6,7,8}","{9,10,11,12}","{13,14,15}"}
并表明它确实按预期工作:
SELECT ((ARRAY_AGG(a::TEXT))[2]::INTEGER[])[2]
FROM (
SELECT ARRAY_AGG(g) AS a
FROM (
SELECT g, ROW_NUMBER() OVER() - 1 AS r
FROM generate_series(1, 15) g
) x
GROUP BY r / 4
) y
结果:6