[英]Running Sums for Multiple Categories in MySQL
I have a table of the form 我有一张表格
Category Time Qty
A 1 20
B 2 3
A 3 43
A 4 20
B 5 25
I need a running total to be calculated by category in MySQL. 我需要在MySQL中按类别计算运行总计。 The result would look something like this: 结果看起来像这样:
Category Time Qty Cat.Total
A 1 20 20
B 2 3 3
A 3 43 63
A 4 20 83
B 5 25 28
Any idea how I could do this efficiently in MySQL? 知道如何在MySQL中有效地做到这一点吗? I have searched far and wide, but all I can find is info on how to insert one single running total in MySQL. 我搜索的范围很广,但我能找到的是有关如何在MySQL中插入一个单独运行总计的信息。 I wonder if there's any way to use GROUP BY or a similar construct to achieve this. 我想知道是否有任何方法可以使用GROUP BY或类似的构造来实现这一目标。
You could calculate the sum in a subquery: 您可以在子查询中计算总和:
select Category
, Time
, Qty
, (
select sum(Qty)
from YourTable t2
where t1.Category = t2.Category
and t1.Time >= t2.Time
) as CatTotal
from YourTable t1
Trading readability for speed, you can use a MySQL variable to hold the running sum: 交易可读性的速度,您可以使用MySQL变量来保持运行总和:
select Category
, Time
, Qty
, @sum := if(@cat = Category,@sum,0) + Qty as CatTotal
, @cat := Category
from YourTable
cross join
(select @cat := '', @sum := 0) as InitVarsAlias
order by
Category
, Time
The ordering is required for this construct to work; 此构造需要排序才能工作; if you need a different order, wrap the query in a subquery: 如果需要不同的顺序,请将查询包装在子查询中:
select Category
, Time
, Qty
, CatTotal
from (
select Category
, Time
, Qty
, @sum := if(@cat = Category,@sum,0) + Qty as CatTotal
, @cat := Category
from YourTable
cross join
(select @cat := '', @sum := 0) as InitVarsAlias
order by
Category
, Time
) as SubQueryAlias
order by
Time
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.