sql >> Base de Datos >  >> RDS >> PostgreSQL

Hacer que 'agrupar por' resulte en múltiples columnas

Puede usar la agregación condicional si se sabe que la cantidad de valores distintos en la columna irt_tlevel es fija.

select 
extract(year from a.created) as Year,
a.testscoreid, 
sum(case when b.irt_tlevel = 'Low' then 1 else 0 end) as Low,
sum(case when b.irt_tlevel = 'Medium' then 1 else 0 end) as Medium,
sum(case when b.irt_tlevel = 'High' then 1 else 0 end) as High,
count(*) as Questions
from asmt.testscores a 
join asmt.questions b on a.questionid = b.questionid
where a.answered = True
group by Year, a.testscoreid
order by Year desc, a.testscoreid