Когда я выполняю этот запрос:
with details AS (
select * from table order by class
)
select t.id, t.gpa,
(select array_to_string(array_agg(class),',')
from details d
where d.id = t.id and d.gpa = t.gpa and rank = 'great')
as great,
(select array_to_string(array_agg(class),',')
from details d
where d.id = t.id and d.gpa = t.gpa and rank = 'high')
as high,
(select array_to_string(array_agg(class),',')
from details d
where d.id = t.id and d.gpa = t.gpa and rank = 'medium')
as medium,
(select array_to_string(array_agg(class),',')
from details d
where d.id = t.id and d.gpa = t.gpa and rank = 'low')
as low
from table t
group by t.id, t.gpa
order by t.gpa
Я получаю результаты:
id gpa great high medium low
----+-----+-------------+----------------------+----------+------------------
1 2.0 spanish english,math,pe
2 3.5 art english,history,tech
3 4.0 art,english spanish pe
Я надеюсь, что вы служите.
ОБНОВЛЕНИЕ: Другой вариант с лучшей производительностью.
select t.id, t.gpa,
a.class as great,
b.class as high,
c.class as medium,
d.class as low
from table t
left join (select id, gpa, array_to_string(array_agg(class),',') as class
from table
where rank = 'great'
group by id, gpa
) a on (a.id = t.id and a.gpa = t.gpa)
left join (select id, gpa, array_to_string(array_agg(class),',') as class
from table
where rank = 'high'
group by id, gpa
) b on (b.id = t.id and b.gpa = t.gpa)
left join (select id, gpa, array_to_string(array_agg(class),',') as class
from table
where rank = 'medium'
group by id, gpa
) c on (c.id = t.id and c.gpa = t.gpa)
left join (select id, gpa, array_to_string(array_agg(class),',') as class
from table
where rank = 'low'
group by id, gpa
) d on (d.id = t.id and d.gpa = t.gpa)
group by t.id, t.gpa, a.class, b.class, c.class, d.class
order by t.gpa