with detail as (
select
gl.title as grade, s.race, s.gender, count(s.student_id) total
from
students s
inner join
student_enrollment se using (student_id)
inner join
school_gradelevels gl on se.school_id = gl.school_id and se.grade = gl.id
where
and se.syear = 2012
and se.end_date is null
and se.school_id = 10
group by 1, 2, 3
order by 1, 2, 3
) agg as (
select grade, array_agg(total) total
from detail
group by grade
)
select
grade,
(select sum(e) from unnest(total) s(e)) total_grade,
total[1,1] + total[2,1] + total[3,1] + total[4,1] + total[5,1] + total[6,1] total_F,
total[1,2] + total[2,2] + total[3,2] + total[4,2] + total[5,2] + total[6,2] total_M,
total[1,1] total_A_F,
total[1,2] total_A_M,
total[1,1] + total[1,2] total_A,
total[2,1] total_B_F,
total[2,2] total_B_M,
total[2,1] + total[2,2] total_B,
total[3,1] total_H_F,
total[3,2] total_H_M,
total[3,1] + total[3,2] total_H,
total[4,1] total_I_F,
total[4,2] total_I_M,
total[4,1] + total[4,2] total_I,
total[5,1] total_M_F,
total[5,2] total_M_M,
total[5,1] + total[5,2] total_MM,
total[6,1] total_W_F,
total[6,2] total_W_M,
total[6,1] + total[6,2] total_W,
from agg