我如何分别获得男性人数和女性人数

时间:2017-05-17 10:34:38

标签: sql database

这是我的代码,我需要分别获得男性和女性的数量

public function getmaletofemaleCountById()
{
    $select = $this->select();
    $select->from($this->_name, array('count(*) AS candidateSum','count(candidate_gender='.MALE.') AS male','count(candidate_gender='.FEMALE.') AS female'));
    $select->joinLeft(array('batch' => DBPREFIX.'batch'), 'batch.batch_training_center=tc_id AND batch.deleted=0', array());
    $select->joinLeft(array('candidate' => DBPREFIX.'candidate'), 'candidate.candidate_batch_id=batch.batch_id AND candidate.deleted=0', array());
    $select->where('tc_id = ?', $this->tc_id);
    $select->where('candidate_gender != ?', 3);
    //$select->group('candidate_gender');
    die($select);

    return $this->fetchRow($select);
}

2 个答案:

答案 0 :(得分:2)

$select->from($this->_name, array('count(*) AS candidateSum','SUM(IF(candidate_gender='.MALE.',1,0)) AS male','SUM(IF(candidate_gender='.FEMALE.',1,0)) AS female'));

您必须使用此更新阵列。 SUM()对于男性和女性都是有条件的。

因此,您的更新代码应如下所示:

public function getmaletofemaleCountById(){
            $select=$this->select();
            $select->from($this->_name, array('count(*) AS candidateSum','SUM(IF(candidate_gender='.MALE.',1,0)) AS male','SUM(IF(candidate_gender='.FEMALE.',1,0)) AS female'));
            $select->joinLeft(array('batch'=>DBPREFIX.'batch'), 'batch.batch_training_center=tc_id AND batch.deleted=0', array());
            $select->joinLeft(array('candidate'=>DBPREFIX.'candidate'), 'candidate.candidate_batch_id=batch.batch_id AND candidate.deleted=0', array());
            $select->where( 'tc_id = ?',$this->tc_id);
            $select->where( 'candidate_gender != ?',3);
            //$select->group('candidate_gender');
            die($select);

            return $this->fetchRow($select);
}

答案 1 :(得分:1)

下面给出的代码适用于我

public function getmaletofemaleCountById()
    {
        $select=$this->select();
        $select->from($this->_name, array('count(candidate.candidate_batch_id) AS candidateSum','SUM(case when candidate_gender='.MALE.' then 1 else 0 end) as maleCount' ,'SUM(case when candidate_gender='.FEMALE.'then 1 else 0 end) as femaleCount','SUM(case when candidate_gender='.TRANSGENDER.'then 1 else 0 end) as transCount'));
        $select->joinLeft(array('batch'=>DBPREFIX.'batch'), 'batch.batch_training_center=tc_id AND batch.deleted=0', array());
        $select->joinLeft(array('candidate'=>DBPREFIX.'candidate'), 'candidate.candidate_batch_id=batch.batch_id AND candidate.deleted=0', array());
        $select->where( 'tc_id = ?',$this->tc_id);

        return $this->fetchRow($select);
        }