我想知道mysql 5.7引擎的工作原理与总和相同。 无法替换查询引擎,因为它不是个人操作。
有人试图通过@set变量函数来解决它,但是我发现很难获得四列中每一列的累加和。
我看了下面的链接,但是有点难以解决。 how to rank over partition in MySql
我的桌子
id a b c d
----------------------------
abs 1 0 0 1
abs 0 1 1 0
abs 1 0 1 0
abs 1 1 1 1
qwe 0 0 0 0
qwe 0 0 0 1
qwe 1 0 1 0
qwe 1 1 0 1
trx 0 1 1 0
trx 1 1 0 0
预期
id a b c d
----------------------------
abs 1 0 0 1
abs 1 1 1 1
abs 2 1 2 1
abs 3 2 3 2
qwe 0 0 0 0
qwe 0 0 0 1
qwe 1 0 1 1
qwe 2 1 1 2
trx 0 1 1 0
trx 1 2 1 0
谢谢。
答案 0 :(得分:0)
您想要每一列的累积总和。为了使它起作用,您需要一列来指定顺序-SQL表表示无序集。
假设您有这样一列,那么通常可以使用以下内容:
select t.*,
(@a := if(@id = id, @a + a, 0)) as a,
(@b := if(@id = id, @b + b, 0)) as b,
(@c := if(@id = id, @c + c, 0)) as c,
(@d := if(@id = id, @d + d, 0)) as d,
@id := id
from (select t.*
from t
order by t.id, ? -- column for the ordering
) t cross join
(select @id := -1, @a := 0, @b := 0, @c := 0 @d := 0) params;
但是,这不能得到保证,因为MySQL不能保证SELECT
中表达式的求值顺序。因此,我认为子查询可能是最简单的方法:
select t.id,
(select sum(t2.a) from t t2 where t2.id = t.id and t2.? <= t.?) as a,
(select sum(t2.b) from t t2 where t2.id = t.id and t2.? <= t.?) as b,
(select sum(t2.c) from t t2 where t2.id = t.id and t2.? <= t.?) as c,
(select sum(t2.d) from t t2 where t2.id = t.id and t2.? <= t.?) as d
from t;