【发布时间】:2022-01-11 09:43:27
【问题描述】:
如何使用 CodeIgniter 的查询构建器方法找到每个部分中的男性和女性人数?
我已经尝试了Count、select、sum 的分组,但我仍然无法达到我想要的结果。
我想要的是获取部门名称、学生总数以及单独的男性和女性人数。我想用 1 个查询来做到这一点。
期望的输出:
| Male | Female |
|---|---|
| Section 1 | 10 |
| Section 2 | 8 |
表架构:
- tbl_section:section_id,section_name
- tbl_student: stud_id,stud_name,gender,section_id(外键)
我的编码尝试:
$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();
原始 SQL 尝试:
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;
结果:只显示 1 种性别 -- 我想同时显示男性和女性。
【问题讨论】:
-
你的表架构是什么?
-
我已经添加了我的表格方案
-
向我们展示您的代码,我们可以更正它。
Count Select Sum with Group没有任何意义。特别是因为SELECT永远是第一位的 -
我已经添加了代码先生.. 我可以计算男性,但我不知道只在 1 个查询中计算女性并显示它们是什么部分。用于excel报告
-
您能否证明您知道如何使用纯 SQL 执行此任务?这始终是第一步。转换为 CodeIgniter 的查询构建器方法是一个不错的选择。这个页面肯定会激发(spoonfeed)你:stackoverflow.com/q/11986617/2943403
标签: php mysql codeigniter group-by aggregate-functions