简体   繁体   中英

Calculate percentage of true bools to false

First of all, I am quite new to MySQL.

I have a table called bike_main, within this table there are two columns; one for date and one for north_bool. I am trying to calculate the percentage of true booleans to false booleans. For example, if four out of 10 rows in north_bool are set to 1 then the result would be 40%. I have tried;

    $northRidersQuery = 'SELECT count(north_bool) as number_of_rows FROM bike_main ORDER BY id DESC LIMIT 1';
    $northRidersResult=mysql_query($northRidersQuery);
    $northRidersDisplay = mysql_fetch_assoc($monthlyRidersResult);

and outputting it with

<h3><?php echo $northRidersDisplay ?></h3>

This does not output anything.

Try this:

while ($northRidersDisplay = mysql_fetch_assoc($monthlyRidersResult)) {
    echo $row["number_of_rows"]; // echo column name
}

COUNT(north_bool) counts the number of rows where north_bool is not NULL . If it's not null, it doesn't care if it's 0 or 1 . If you want to count just 1 values, use SUM(north_bool) .

$northRidersQuery = 'SELECT SUM(north_bool)*100/COUNT(*) AS north_pct
                     FROM bike_main';
$northRidersResult = mysql_query($northRidersQuery);
$northRidersRow = mysql_fetch_assoc($northRidersResult);
echo "<h3>{$northRidersRow['north_pct']}%</h3>";

Finally, you need to use $northRidersRow['north_pct'] to access a column in the results.

You may try something as

$qry = "select (x.true_tot/x.tot)*100 as perc 
        from ( select sum(north_bool=1) as true_tot, count(*) as tot from test ) x " ;
$result = mysql_query($qry);
$result_set = mysql_fetch_assoc($result);
echo '<h3>'.$result_set["perc"].'</h3>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM