Karem
Karem

Reputation: 18103

SQL/PHP: Counting average male/females

$sql = $connect->prepare("SELECT e.ID, u.sex FROM discos_events e
INNER JOIN discos_events_guests eg ON (e.ID = eg.eID)
INNER JOIN users u ON (eg.uID = u.id)
WHERE 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 this be done any simpler?

If not, this does not work properly, if there's two males and 0 females, $averageMales return 1 and $averageFemales return 0.

I want it to return in procentages, e.g 100% now when theres not any females, and females 0%.

Upvotes: 1

Views: 598

Answers (2)

monsieur_h
monsieur_h

Reputation: 1380

Make two queries: one getting the females, on getting the total. Then divide. By the way, there is a COUNT(*) function in SQL wich is way faster than executing a full query and then fetching it with $sql->rowCount();

Counts the total number of guests:

"SELECT COUNT(*)
FROM discos_events e
INNER JOIN discos_events_guests eg ON (e.ID = eg.eID)
INNER JOIN users u ON (eg.uID = u.id)
WHERE e.dID =:id"

Counts the number of females:

"SELECT COUNT(*)
FROM discos_events e
INNER JOIN discos_events_guests eg ON (e.ID = eg.eID)
INNER JOIN users u ON (eg.uID = u.id)
WHERE e.dID =:id
AND eg.sec='female'"

Upvotes: 2

jkj
jkj

Reputation: 2611

No need to use separate queries:

SELECT count(males.id) / (count(males.id) + count(females.id)) * 100 AS male_percentage
FROM discos_events
JOIN discos_events_guests ON discos_events_guests.eID = discos_events.ID
LEFT JOIN users males ON males.sex = 'male' AND males.id = discos_events_guests.uID
LEFT JOIN users females ON females.sex = 'female' AND females.id = discos_events_guests.uID
WHERE discos_events.dID = :id

Upvotes: 3

Related Questions