2017-08-24 96 views
0
select ds.school_name_np, 
case 
    when (ds.gender_id = 1 and ds.class=1) then ds.no_of_student 
end as boys_1, 
case 
    when (ds.gender_id = 2 and ds.class=1) then ds.no_of_student 
end as girls_1, 
case 
    when (ds.gender_id = 1 and ds.class=2) then ds.no_of_student 
end as boys_2, 
case 
    when (ds.gender_id = 2 and ds.class=2) then ds.no_of_student 
end as girls_2 
from data_047_differntly_abled_school_summary ds 
-- GROUP BY school_name_np, gender_id, class, no_of_student 
ORDER BY school_name_np 

我有产生如下结果上面的查询:PostgreSQL的查询行合并成一个

enter image description here

如何获得同样的学习成绩在单行?

+0

'array_agg'或'string_agg'和'GROUP BY ... HAVING ...' –

回答

1

每列只需使用聚合函数:

select ds.school_name_np, 
     MAX(case when ds.gender_id = 1 and ds.class=1 then s.no_of_student end) as boys_1, 
     MAX(case.....), 
     ... 
from data_047_differntly_abled_school_summary ds 
GROUP BY school_name_np 
ORDER BY school_name_np 
+0

谢谢@sagi – sandeshsays