您可以在子查询中计算总和:
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
交易可读性的速度,您可以使用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
此构造需要排序才能工作;如果您需要不同的顺序,请将查询包装在子查询中:
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