обычно я считаю заглавные буквы в именах столбцов вредными, поэтому я проигнорировал эту часть вашего запроса.
ваши данные:
create temp table d(id int,type text,col1 int,col2 int ,col3 int);
insert into d values (1,'a',5,2,3),(1,'b',2,1,3),(2,'a',4,4,3),(2,'c',7,6,4);
один из способов сделать это - конвертировать в EAV, а затем сделать разворот на этом:
with eav as (
select id,type,'col1' as col,col1 as val from d
union all
select id,type,'col2',col2 from d
union all
select id,type,'col3',col3 from d)
, ca as (select id,col, val from eav where type='a')
, cb as (select id,col, val from eav where type='b')
, cc as (select id,col, val from eav where type='c')
select id,col,ca.val as a ,cb.val as b, cc.val as c
from ca
full outer join cb using (id,col)
full outer join cc using (id,col)
order by id,col;
результат: (после \pset null 'null' in psql
)
id | col | a | b | c
----+------+---+------+------
1 | col1 | 5 | 2 | null
1 | col2 | 2 | 1 | null
1 | col3 | 3 | 3 | null
2 | col1 | 4 | null | 7
2 | col2 | 4 | null | 6
2 | col3 | 3 | null | 4
или это может быть устроено так:
with eav as (
select id,type,'col1' as col,col1 as val from d
union all
select id,type,'col2',col2 from d
union all
select id,type,'col3',col3 from d)
, ca as (select id,col, val as a from eav where type='a')
, cb as (select id,col, val as b from eav where type='b')
, cc as (select id,col, val as c from eav where type='c')
select *
from ca
full outer join cb using (id,col)
full outer join cc using (id,col)
order by id,col;