如何 select 整数和数组元素?

How can I select integers and array elements?

我能够 select 将 "col3" 中的重复值放入一个数组中,并使用以下方法按 "col1"、"col2" 排列它们:

select "col1", "col2", array_agg("col3"  order by "col1", "col2") as myArray FROM 
     myTable group by "col1", "col2"

接下来,我想 select 数组的前两个元素(因此它们出现在自己的列中)并继续 "col1"、"col2" 排列它们像这样:

select "col1", "col2", element[1], element[2] from 
    (select "col1", "col2", array_agg("col3"  order by "col1", "col2") as myArray FROM 
         myTable group by "col1", "col2") as  vv(element)

但是,我收到以下错误:

ERROR:  cannot subscript type integer because it is not an array

有没有办法转换 "col1" 和 "col2" 的整数值,以便我可以将数组元素放入由 "col1" 和 "col2" 组织的单独列中?

您的 table 别名 vv(element) 是错误的,因为内部查询有 3 列,而不仅仅是一列。通过仅指定一列,您仅将第一列重命名(col1element),而其他两列在内部查询中保留其原始名称。

因此您的别名需要为所有三列提供名称:

select "col1", "col2", element[1], element[2] 
from (
   select "col1", "col2", array_agg("col3"  order by "col1", "col2") as myArray 
   FROM myTable 
   group by "col1", "col2"
) as vv(co1, col2, element);

vv(co1, col2, element) 本质上是将 myarray 重命名为 element.

由于内部查询中的所有列都有专有名称,因此您实际上不需要 table 别名中的列别名:

select "col1", "col2", myarray[1] as element_one, myarray[2]  as element_two
from (
   select "col1", "col2", array_agg("col3"  order by "col1", "col2") as myArray 
   FROM myTable 
   group by "col1", "col2"
) as vv;