我有一个表格,其ID和值如下所示。是否有可能获得另一列,当我们沿着这条线行时,该值除以累积平均值?
original table : t1
+----+----------------------+
| id | Val |
+----+---------------------+-
| 1 | NULL |
| 2 | 136 |
| 3 | 42 |
table i want to get
+----+---------------------+-----------------------------+
| id | Val | VAL/(AVG(VAL) ) |
+----+---------------------+-----------------------------+
| 1 | NULL | NULL |
| 2 | 136 | 136/((136+0)/2)=2.000 |
| 3 | 42 | 42/((42+136+0)/3)=0.708 |
这是我的查询:
SELECT t1.id, t1.Val, Val/AVG(t1.Val)
FROM followers t1
JOIN followers t2
ON t2.id <= t1.id
group by t1.id;
然而我得到了这个:
+----+---------------------+----------------------+
| id | Val | VAL/(AVG(VAL) ) |
+----+---------------------+----------------------+
| 1 | NULL | NULL |
| 2 | 136 | 1.0000 |
| 3 | 42 | 1.0000 |
似乎AVG(Val)从col Val返回相同的值。
我希望在这里做类似这个链接的东西,但不是总和,我想要平均。 MySQL SELECT function to sum current data
我重新实现了编辑,并将带有NULL的行考虑在内:
+----+---------------------+---------------------+
| id | Val | VAL/(AVG(VAL) ) |
+----+---------------------+----------------------+
| 1 | NULL | NULL |
| 2 | 136 | 1.0000 |<---need this to = 2.000
| 3 | 42 | 0.4719 |<---need this to = 0.708
SELECT t1.id, t1.Val, t1.Val/(SUM(t2.Val)/(t1.id)) AS C
FROM followers t1
JOIN followers t2
ON t2.id <= t1.id
group by t1.id;
答案 0 :(得分:0)
我认为您需要t2.val
中的avg()
:
SELECT t1.id, t1.Val, t1.Val/AVG(t2.Val)
FROM followers t1 JOIN
followers t2
ON t2.id <= t1.id
group by t1.id;
编辑:
迈克·布兰德是正确的,以上是一个糟糕的方式来做你想要的。在MySQL中,您可以使用变量执行相同的操作:select t.id, t.val,
(case when (@n := @n + 1) is null then null
when (@cumval := @cumval + val) is null then null
else t.val / (@cumval / @n)
end)
from followers t cross join
(select @n := 0, @cumval := 0) vars
order by t.id;
这可能会错误地使用val
的NULL值,但它提供了在MySQL中更快速地进行计算的想法。