优先权无界的MYSQL移动平均计算
我有一个包含三列的表:id、a、B。我想用下面的计算填充E列 **Cols C和D在我的表中是不存在的,它们是我希望创建并放入查询中的子查询,这将帮助我填充col E。看起来,C和D是移动平均值,但没有太多的例子可以帮助我优先权无界的MYSQL移动平均计算,mysql,sql,join,sql-update,subquery,Mysql,Sql,Join,Sql Update,Subquery,我有一个包含三列的表:id、a、B。我想用下面的计算填充E列 **Cols C和D在我的表中是不存在的,它们是我希望创建并放入查询中的子查询,这将帮助我填充col E。看起来,C和D是移动平均值,但没有太多的例子可以帮助我 Table followers id A B C D E _ _ _ _
Table followers
id A B C D E
_ _ _ _ _ _
0 1 2 A0/(AVG(A0)) #1/1 B0/(AVG(B0)) (C0+D0)/2
1 2 2 A1/(AVG(A1,A0)) #2/((2+1)/2) B1/(AVG(B1,B0)) (C1+D1)/2
2 3 2 A2/(AVG(A1,A2,A0)) #3/((3+2+1)/3) B2/(AVG(B1,B2,B0)) (C2+D2)/2
如何为此编写查询?我相信我需要一个左外连接到它自己
我想把C列的计算设为一个变量,D列的计算设为另一个变量
对于C列,这是我的方法:
update followers f left outer join
followers f2...
我不知道该怎么继续,因为我不知道该怎么做
f.id=f2.id where f2.id between f.id and f2.id+1.
我获得了一些使用此查询的帮助,但它不起作用:
UPDATE
f,
(
SELECT AVG(f.A)
FROM (
SELECT f.A
FROM f
WHERE f.id <= f.id
) as t
) as temp,
(
SELECT AVG(f.B)
FROM (
SELECT f.B
FROM f
WHERE f.id <= f.id
) as t2
) as temp2
SET
f.C =((f.A/temp) + (f.B/temp2))/2;
我将为此使用子查询
SELECT id, A, B, C, D, (C+D)/2 E FROM (
SELECT id, A, B,
(A/(SELECT AVG(A) FROM table t2 WHERE t2.id <= t1.id)) C,
(B/(SELECT AVG(B) FROM table t2 WHERE t2.id <= t1.id)) D
FROM table t1 ) t3
我将使用变量来处理这个问题
select t.id, t.A, t.B,
(case when (@n := @n + 1) is null then null
when (@c := @c + a) is null then null
else t.A / (@c / @n)
end) as C,
(case when (@d := @d + b) is null then null
else t.B / (@d / @n)
end) as D,
(t.A / (@c / @n)) + (t.B / (@d / @n)) as E
from table t cross join
(select @c := 0, @d := 0, @n := 1) vars
order by id;
您可以使用连接将其放入update语句中
对于您的第一个查询,我假设您只是填充列E?因为有多个表,所以第一个查询是否需要联接?@jenn两个查询都填充所有列。第一次查询不需要连接,因为子查询用于访问t2I。我已经有了id、a列和B列。我不需要C列或D列。我只需要根据id、a和B中的数字填充E。此查询是否适用?我只是把C和D放在那里以便于参考,但这些列不存在。@jenn是的,它应该可以工作,如果您不需要C和D,那么从select语句中省略。如果我只是更新列E,我应该添加update f SET col E=select。。。其中f是表名。对不起,请详细说明如何将其放入带有联接的update语句中。如果f是我的原始表,那么它不会是第二个表吗?我的列E中的所有行都为NULL,这不应该是第二个表case@jenn . . . 如果子查询有效,那么它应该将相同的值分配到表中。但是如果任何列包含空值,您将得到空值。我如何忽略空值?@jenn。将A不为null和B不为null的位置添加到子查询中,或者在计算中使用coalesce,以便将它们视为0。这取决于你想用它们做什么。
select t.id, t.A, t.B,
(case when (@n := @n + 1) is null then null
when (@c := @c + a) is null then null
else t.A / (@c / @n)
end) as C,
(case when (@d := @d + b) is null then null
else t.B / (@d / @n)
end) as D,
(t.A / (@c / @n)) + (t.B / (@d / @n)) as E
from table t cross join
(select @c := 0, @d := 0, @n := 1) vars
order by id;
update table t join
(select t.id, t.A, t.B,
(case when (@n := @n + 1) is null then null
when (@c := @c + a) is null then null
else t.A / (@c / @n)
end) as C,
(case when (@d := @d + b) is null then null
else t.B / (@d / @n)
end) as D,
(t.A / (@c / @n)) + (t.B / (@d / @n)) as E
from table t cross join
(select @c := 0, @d := 0, @e := 0, @n := 1) vars
order by id
) newvals
on t.id = newvals.id
set t.C = newvals.C,
t.D = newvals.D,
t.E = newvals.E;