在我的SQL数据库中,我有一个表,其中一些项目的列为ENUM类型,有3个选项:'pending','discount','received'
如何打印“已收到”选项的人口百分比,例如(在我的表格中,我有40%的“已收到”选项被选中)?
谢谢!
答案 0 :(得分:0)
获取每个的总数非常简单(假设你的枚举列被称为'status'并且有一个名为id的列):
SELECT status, count(id) FROM myTable GROUP BY status;
虽然可以编写查询来计算实际百分比,但最简单的事情就是自己做数学
如果您选择使用mysqli来运行查询,代码将是这样的:
// 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'];
}
这将为您提供类似['pending' => 100, 'discount' => 200, 'received' => 50]
)的数组:
$total = $result['pending'] + $result['discount'] + $result['received'];
$pctPending = ($result['pending']*100)/$total;
等等。您当然必须调整代码以匹配结果的返回方式,但无论如何数学都适用。