mysql: avg vs sum/count

rom*_*rom 4 mysql average sum count

I have 4 variables:

  • amdt_adopt
  • com_amdt_adopt
  • amdt_tabled
  • com_amdt_tabled

I want to compute the average of the ratio:

(amdt_adopt - com_amdt_adopt) / (amdt_tabled - com_amdt_tabled)
Run Code Online (Sandbox Code Playgroud)

If I use the built-in avg function:

select avg((amdt_adopt - com_amdt_adopt) / (amdt_tabled - com_amdt_tabled)) as final_res
from europolix.act_act
where validated=2 and com_amdt_adopt>0 and amdt_adopt>0 and com_amdt_tabled>0 and amdt_tabled>0;
Run Code Online (Sandbox Code Playgroud)

I get 0.44771942.

If I use a sum and then divides by count:

select 
(
    select sum((amdt_adopt - com_amdt_adopt) / (amdt_tabled - com_amdt_tabled))
    from europolix.act_act
    where validated=2 and com_amdt_adopt>0 and amdt_adopt>0 and com_amdt_tabled>0 and amdt_tabled>0
) 
/ 
(
    select count(*) 
    from europolix.act_act
    where validated=2 and com_amdt_adopt>0 and amdt_adopt>0 and com_amdt_tabled>0 and amdt_tabled>0
) as final_res;
Run Code Online (Sandbox Code Playgroud)

I get 0.20883803.

I have different results but these two queries are supposed to be equivalent! What's wrong?

EDIT

Cast to decimal as suggested:

select avg((cast(amdt_adopt - com_amdt_adopt as decimal(8,3)))  / (cast(amdt_tabled - com_amdt_tabled as decimal(8,3)))) as final_res
from europolix.act_act
where validated=2 and com_amdt_adopt>0 and amdt_adopt>0 and com_amdt_tabled>0 and amdt_tabled>0;

select 
(
    select sum((cast(amdt_adopt - com_amdt_adopt as decimal(8,3))) / (cast(amdt_tabled - com_amdt_tabled as decimal(8,3))))
    from europolix.act_act
    where validated=2 and com_amdt_adopt>0 and amdt_adopt>0 and com_amdt_tabled>0 and amdt_tabled>0
) 
/ 
(
    select count(*) 
    from europolix.act_act
    where validated=2 and com_amdt_adopt>0 and amdt_adopt>0 and com_amdt_tabled>0 and amdt_tabled>0
) as final_res;
Run Code Online (Sandbox Code Playgroud)

Still same result :(.

lp_*_*lp_ 5

如果您在 avg 中使用的某些列的记录中有 NULL 值,则 avg 或 sum/count 的结果可能很容易不同。

例如:

create table t (id int, x int, y int);

insert into t (id, x, y) values (1, 1, 1);
insert into t (id, x, y) values (2, 2, 3);
insert into t (id, x, y) values (3, 3, 4);
insert into t (id, x, y) values (4, NULL, NULL);


select avg(x), sum(x), count(x), count(*), sum(x)/count(*) from t;
Run Code Online (Sandbox Code Playgroud)

会给你:

AVG(X)  SUM(X)  COUNT(X)    COUNT(*)    SUM(X)/COUNT(*)
2       6       3           4           1.5
Run Code Online (Sandbox Code Playgroud)

同样,AVG 不会考虑除以零的位置。

例如

select avg(x/(y-x)) from t where x>0 and y>0;
2.5

select sum(x/(y-x))/count(*) from t where x>0 and y>0;
1.66666667
Run Code Online (Sandbox Code Playgroud)

一种解决方案可能是在这样的条件下使用 avg:

select avg(if(y-x=0, 0, x/(y-x))) from t where x>0 and y>0;
1.66666667
Run Code Online (Sandbox Code Playgroud)

一个例子可以在这里看到

[编辑] 更新以考虑除以零的可能性