我有以下查询,该查询不起作用:
$sql = "SELECT dma, COUNT(*) as dma_count, round(dma_count/32434 * 100) as dma_percent FROM {$table} where dma != '0' GROUP BY dma ORDER BY dma_count DESC;";
(我知道)它不起作用的原因是因为我正在使用dma_count
这一部分round(dma_count/32434 * 100)
。
正确的方法是什么?
编辑:
额外的挑战。而不是使用32434,我想使用一个变量。我得到这样的变量:
$get_total = "SELECT count(DISTINCT `exuid`) from {$table};";
$total = $dbh->query($get_total)->fetchAll(PDO::FETCH_ASSOC);
这样我的查询就变成了(注释中建议了修复程序)
$sql = "SELECT dma, COUNT(*) as dma_count, round(COUNT(*)/{$total} * 100) as dma_percent FROM {$table} where dma != '0' GROUP BY dma ORDER BY dma_count DESC;";
这不起作用,因为我认为$total
格式错误。我怎样才能解决这个问题?
再次编辑:
知道了!$total
只是我的行数,所以我有了它。
SELECT dma, COUNT(*) as dma_count, round(COUNT(*)/(SELECT COUNT(*) FROM {$table}) * 100,2) as dma_percent FROM {$table} where dma != '0' GROUP BY dma ORDER BY dma_count DESC;"
您可以在方程式中使用COUNT(*)而不是别名,或最终回答子查询。通常,如果可以使用联接,请避免使用子查询。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句