2017-05-17 35 views
-3

這裏是我的代碼,我需要得到男性和女性的數量分別我怎樣才能得到伯爵男性和女性分別計數

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); 
} 
+1

選擇 COUNT(CASE WHEN candidate_gender = '男',那麼ID END)AS男性, COUNT(CASE WHEN candidate_gender ='FEMALE'THEN ID END)AS女性, COUNT(*)AS合計 FROM your_table; –

回答

1
$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

下面給出的代碼對我的作品

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); 
     } 
相關問題