【问题标题】:使用 CodeIgniter 计算每组中的男性和女性总数
【发布时间】:2022-01-11 09:43:27
【问题描述】:

如何使用 CodeIgniter 的查询构建器方法找到每个部分中的男性和女性人数?

我已经尝试了Countselectsum 的分组,但我仍然无法达到我想要的结果。

我想要的是获取部门名称、学生总数以及单独的男性和女性人数。我想用 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


【解决方案1】:

您希望按部分 id 进行分组,然后在 select 中计算与每个分组的部分 id 相关的两个条件计数。

原始 SQL 如下所示:(db-fiddle demo)

SELECT sec.section_name, SUM(gender = 'M') males, SUM(gender = 'F') females
FROM tbl_section AS sec
JOIN tbl_student AS stu ON sec.section_id = stu.section_id
GROUP BY section_name

要将其转换为 CI 的查询构建器方法:

return $this->db
    ->select("sec.section_name section, SUM(gender = 'M') males, SUM(gender = 'F') females")
    ->from('tbl_section sec')
    ->join('tbl_student stu', 'sec.section_id = stu.section_id')
    ->group_by('section_name')
    ->get()
    ->result();

【讨论】:

    猜你喜欢
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    相关资源
    最近更新 更多