SQL/PHP: Counting average male/females -
$sql = $connect->prepare("select e.id, u.sex discos_events e inner join discos_events_guests eg on (e.id = eg.eid) inner join users u on (eg.uid = u.id) e.did =:id"); $sql->bindvalue(":id", $cid); $sql->execute(); $total = $sql->rowcount(); $male = 0; $female = 0; while($sex = $sql->fetch()){ if($sex["sex"] == "male"){ $male++; }else{ $female++; } } $averagemales = $male/$total; $averagefemales = $female/$total;
can done simpler?
if not, not work properly, if there's 2 males , 0 females, $averagemales return 1 , $averagefemales return 0.
i want return in procentages, e.g 100% when theres not females, , females 0%.
no need use separate queries:
select count(males.id) / (count(males.id) + count(females.id)) * 100 male_percentage discos_events join discos_events_guests on discos_events_guests.eid = discos_events.id left join users males on males.sex = 'male' , males.id = discos_events_guests.uid left join users females on females.sex = 'female' , females.id = discos_events_guests.uid discos_events.did = :id
Comments
Post a Comment