[英]Use declared “AS” variable in SQL query
I have the following query, which doesn't work: 我有以下查询,该查询不起作用:
$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;";
The reason (I know) it doesn't work is because I'm using dma_count
in this part round(dma_count/32434 * 100)
. 原因(我知道)它不起作用是因为我在这一部分
round(dma_count/32434 * 100)
使用了dma_count
round(dma_count/32434 * 100)
。
What's the correct way to do this? 正确的方法是什么?
EDIT: 编辑:
Additional challenge. 额外的挑战。 Instead of using 32434, I want to use a variable.
我不想使用32434,而是要使用变量。 I get the variable like this:
我得到这样的变量:
$get_total = "SELECT count(DISTINCT `exuid`) from {$table};";
$total = $dbh->query($get_total)->fetchAll(PDO::FETCH_ASSOC);
so my query becomes (with the fix recommended in the comments) 这样我的查询就变成了(注释中建议了修复程序)
$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;";
This doesn't work because I think $total
is in the wrong format. 这不起作用,因为我认为
$total
的格式错误。 How can I fix this? 我怎样才能解决这个问题?
EDIT AGAIN: 再次编辑:
Got it! 得到它了!
$total
is just the count of my rows, so I have this instead. $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;"
you can use COUNT(*) in the equation instead of the alias, or the finial answer a sub query. 您可以在方程式中使用COUNT(*)代替别名,或最终回答子查询。 In general avoid sub queries if you can use a join.
通常,如果可以使用联接,请避免使用子查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.