我有一个包含以下记录的表,2列,col1id和col1:
AA1 TextAA1
AA2 TextAA2
AA3 TextAA3
AB1 TextAB1
AC1 TextAC1
BA1 TextBA1
BA2 TextBA2
BA3 TextBA3
BB1 TextBB1
BC1 TextBC1
CA1 TextCA1
CA2 TextCA2
CA3 TextCA3
CB1 TextCB1
CC1 TextCC1
我需要为输出创建一个这样的表:
TextAA1, TextAA2, TextAA3
TextBA1, TextBA2, TextBA3
TextCA1, TextCA2, TextCA3
除了将它们分组为AA1-3,BA1-3等这一事实外,没有什么可以将记录联系起来。其他记录?B?和?C?可以忽略。
我查看了包括交叉表(已安装)在内的各种答案,并尝试使用联接进行查询无效。
以下是我尝试过的一个示例:
SELECT col1 as a1, row_number() OVER(ORDER BY col1id ASC) as a2
FROM table01
WHERE col1id LIKE '_A_'
JOIN (
SELECT col2 as c1, row_number() OVER(ORDER BY col1id ASC) as c2
FROM table01
WHERE col1id LIKE '_A_') ON a2 = c2
但我无法克服JOIN错误。
我该怎么做? 提前谢谢,
答案 0 :(得分:3)
使用array_agg()
按col1
的第一个字母聚合col1id
组中的值:
select arr[1] as a1, arr[2] as a2, arr[3] as a3
from (
select array_agg(col1 order by col1id) as arr
from table01
where col1id like '_A_'
group by left(col1id, 1) -- first letter of col1id
order by 1
) sub