我想制作另一个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 count desc
limit 5
这个想法是列出前5个访问者国家并计算每个国家/地区的百分比(vwr_cntry)。我期待这样的事情:
+---------------+---------+-----+
| Country |count | % |
+---------------+---------+-----+
|Thailand |2314 | |
+---------------+---------+-----+
|United States |957 | |
+---------------+---------+-----+
|Japan |645 | |
+---------------+---------+-----+
|United Kingdom |70 | |
+---------------+---------+-----+
|China |52 | |
+---------------+---------+-----+
但它会抛出错误:'字段列表'中的未知列'count'
答案 0 :(得分:1)
这样的事情应该有效:
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
这只是一个简单的GROUP BY
查询。它使用非相关子查询来查找总行数,用于计算百分比。
答案 1 :(得分:0)
我首先进入前5个国家,例如:
SELECT vwr_cntry, COUNT(vwr_id) AS 'counts'
FROM viewer_log
GROUP BY vwr_cntry
ORDER BY COUNT(vwr_id) DESC LIMIT 5;
然后,将其包装到另一个查询中以计算sum,e.h。:
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;