简体   繁体   中英

postgresql query merge rows into one

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

I have the above query that generates result as follows:

在此处输入图片说明

How do I get results for the same school in a single row?

Simply use an aggregation function on each column:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM