How can I find the number of males and females in each section using CodeIgniter's query builder methods?
I've already tried Count, select, sum with grouping, but I still cannot achieve my desired result.
What I want is to get the section name, its total students, and its separate male and female counts. I want do this with 1 query.
Desired output:
| Male | Female |
|---|---|
| Section 1 | 10 |
| Section 2 | 8 |
Table Schema:
- tbl_section: section_id, section_name
- tbl_student: stud_id,stud_name,gender,section_id(foreign key)
My coding attempt:
$total =$this->db
->selectCount('gender')
->from(tbl_student)
->join('tbl_section','tbl_student.section_id = tbl_section.section_id)
->where('tbl_student.gender = "male")
->get()
->result_array();
Raw SQL attempt:
select section.section_name,count(stud_id)
from tbl_student
join section on tbl_student.section_id=section.section_id
where tbl_student.gender = "Male"
group by section.section_id;
Outcome: Only 1 gender displayed -- I want to display both male and female.