简单表“测试”:
Name Value
A 2
A 3
B 2
B 3
B 5
C 7
通过简单的查询,我可以得到以下结果:
按名称从测试组中选择名称,计数(*),总和(值),平均值(值)
Count Sum Avg
A 2 5 2,50
B 3 10 3,33
C 1 7 7,00
总计数,总和和平均值也很容易:
从测试中选择计数(*),总和(值),平均值(值)
6 22 3,67
但是如何查询平均值的总和?
12,83 = 2,5 + 3,33 + 7,00
需要的结果:
Count Sum Avg Avg / 12,83 * 100
A 2 5 2,50 19% = 2,50 / 12,83 * 100
B 3 10 3,33 26%
C 1 7 7,00 55%
答案 0 :(得分:1)
计算聚合的聚合需要两个步骤,即子查询。 整个12.83计算独立于任何其他行,因此必须将其放入另一个子查询中:
SELECT COUNT(Value) AS Count,
SUM(Value) AS Sum,
AVG(Value) AS Avg,
AVG(Value) / (SELECT SUM(Avg)
FROM (SELECT AVG(Value) AS Avg
FROM Test
GROUP BY Name)
) * 100 AS AvgPercentage
FROM Test
GROUP BY Name
答案 1 :(得分:0)
SQLite中最简单的方法是使用CTE:
with t as (
select Name, count(*) as cnt, sum(Value) as sumv, avg(Value) as avgv
from test
group by Name
)
select t.*, (avgv / tt.sumavgv) as ratio
from t cross join
(select sum(avgv) as sum_avgv from t) tt;