duanjiao6731 2016-11-07 23:53
浏览 25
已采纳

使用PHP计算ENUM类型列的百分比

In my SQL database I have one table with some items with a column that are ENUM type and has 3 options: 'pending', 'discount', 'received'

How can I print the population percentage of 'received' option, like (In my table I have 40% of 'received' option that are selected) ?

Thank you!

  • 写回答

1条回答 默认 最新

  • doucao1066 2016-11-08 02:25
    关注

    To get the totals for each is pretty simple (assuming your enum column is called 'status' and has a column called id):

    SELECT status, count(id) FROM myTable GROUP BY status;
    

    While it would be possible to write your query to calculate the actual percentages, the simplest thing from there is to do the math yourself

    If you choose to use mysqli to run your query, the code would be something like this:

    // create mysqli connection
    $mysqli = new mysqli("example.com", "user", "password", "database");
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }
    
    $res = $mysqli->query("SELECT status, count(id) AS subtotal FROM myTable GROUP BY status");
    $totals = array();
    while ($row = $res->fetch_assoc()) {
        $totals[$row['status']] = $row['subtotal'];
    }
    

    This will give you an array like ['pending' => 100, 'discount' => 200, 'received' => 50]):

    $total = $result['pending'] + $result['discount'] + $result['received'];
    $pctPending = ($result['pending']*100)/$total;
    

    ans so forth. You will of course have to adjust the code to match how your results come back, but the math applies regardless.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度