使用mysql计算总计数的百分比
我想制作另一个sum数组(从count开始)。然后计算它旁边的百分比。于是我写道:使用mysql计算总计数的百分比,mysql,Mysql,我想制作另一个sum数组(从count开始)。然后计算它旁边的百分比。于是我写道: select vwr_cntry, COUNT(vwr_id) as count1 from viewer_log where not vwr_cntry = '' group by vwr_cntry Union all select 'SUM' vwr_cntry, COUNT(count1)//cannot count the 'count1' from viewer_log order by cou
select vwr_cntry, COUNT(vwr_id) as count1 from viewer_log
where not vwr_cntry = ''
group by vwr_cntry
Union all
select 'SUM'
vwr_cntry, COUNT(count1)//cannot count the 'count1'
from viewer_log
order by count desc
limit 5
这个想法是列出前五名游客的国家,并计算每个国家的百分比(vwr_cntry)。我期待这样的事情:
+---------------+---------+-----+
| Country |count | % |
+---------------+---------+-----+
|Thailand |2314 | |
+---------------+---------+-----+
|United States |957 | |
+---------------+---------+-----+
|Japan |645 | |
+---------------+---------+-----+
|United Kingdom |70 | |
+---------------+---------+-----+
|China |52 | |
+---------------+---------+-----+
但它抛出了一个错误:字段列表中的未知列“count”我首先得到前5个国家,例如:
SELECT vwr_cntry, COUNT(vwr_id) AS 'counts'
FROM viewer_log
GROUP BY vwr_cntry
ORDER BY COUNT(vwr_id) DESC LIMIT 5;
然后,将其包装到另一个查询中以计算总和,例如:
SELECT a.vwr_cntry, a.counts, SUM(a.counts) as 'sums'
FROM (
SELECT vwr_cntry, COUNT(vwr_id) AS 'counts'
FROM viewer_log
GROUP BY vwr_cntry
ORDER BY COUNT(vwr_id) DESC LIMIT 5
) a;
然后,添加计算百分比的公式,例如:
SELECT b.vwr_cntry, b.counts, b.sums, (b.counts/b.sums)*100 AS 'percentage'
FROM (
SELECT a.vwr_cntry, a.counts, SUM(a.counts) as 'sums'
FROM (
SELECT vwr_cntry, COUNT(vwr_id) AS 'counts'
FROM viewer_log
GROUP BY vwr_cntry
ORDER BY COUNT(vwr_id) DESC LIMIT 5
) a
) b;
像这样的方法应该会奏效:
SELECT
vwr_cntry,
COUNT(*) AS cntry_cnt,
100.0 * COUNT(*) / (SELECT COUNT(*) FROM viewer_log) AS pct
FROM viewer_log
GROUP BY vwr_cntry
ORDER BY COUNT(*) DESC
LIMIT 5
这只是一个简单的
分组查询。它使用一个非相关子查询来查找总行数,用于计算百分比。请参见第二部分vwr\u cntry的“您是否错过了一个组?”谢谢您的建议,但它仍然有错误。我认为这不能指“count1”谢谢,但根据人工计算,泰国游客的百分比应该是57%。但是从你的脚本来看只有0.01。它汇总了所有的行,而不仅仅是来自cntry的行_cnt@Wilf对不起,我忘了乘以100。