如何在mysql 5.7中使用分区求和(withhout window函数)
我想知道MySQL5.7引擎是如何工作的,与“部分求和”相同。 无法替换查询引擎,因为它不是个人操作 有人试图通过@set变量函数来解决这个问题,但我发现很难为这四列中的每一列获得累积和 我查看了下面的链接,但它有点难以解决。 我的桌子如何在mysql 5.7中使用分区求和(withhout window函数),mysql,sql,window-functions,mysql-5.7,Mysql,Sql,Window Functions,Mysql 5.7,我想知道MySQL5.7引擎是如何工作的,与“部分求和”相同。 无法替换查询引擎,因为它不是个人操作 有人试图通过@set变量函数来解决这个问题,但我发现很难为这四列中的每一列获得累积和 我查看了下面的链接,但它有点难以解决。 我的桌子 id a b c d ---------------------------- abs 1 0 0 1 abs 0 1 1 0 abs 1
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
提前感谢。您需要每列的累计金额。为了使其工作,您需要一个列来指定排序-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;
您需要每个列的累积总和。为了使其工作,您需要一个列来指定排序-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;
感谢您以正确的方式更正问题@BarbarosÖzhan感谢您以正确的方式更正问题@BarbarosÖzhan谢谢!我会试试的,我有一个专栏要订购——嗨,戈登,我试过了,但没用。错误消息:t不存在,我想是因为表是我查询中的子查询@장수영 . . . t只是表名的占位符,问题中没有提到。谢谢!我会试试的,我有一个专栏要订购——嗨,戈登,我试过了,但没用。错误消息:t不存在,我想是因为表是我查询中的子查询@장수영 . . . t只是表名的占位符,问题中没有提到。