Snippet : Calculer des pourcentages Mysql + Codeigniter

Pour une table donnée contenant :

– firstname

– toto
– michel
– francois
– hugette
– micheline

– gender

– male
– male
– male
– female
– female

On veut extraire les pourcentages par genre. Voici une requête possible :

$this->table = 'users';
$q = $this->db->query("SELECT total, gender, number, ( 100 * number / total ) AS percentage FROM ( SELECT COUNT(firstname) AS total FROM ".$this->table." ) AS total, ( SELECT COUNT(firstname) AS number, gender FROM ".$this->table." GROUP BY gender ) as genders");

Source : http://stackoverflow.com/questions/7038483/get-average-male-and-femal-for-user-table-mysql


Permalien : Snippet : Calculer des pourcentages Mysql + Codeigniter