Anda dapat menghitung jumlah dalam subkueri:
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
Memperdagangkan keterbacaan untuk kecepatan, Anda dapat menggunakan variabel MySQL untuk menahan jumlah berjalan:
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
Pemesanan diperlukan agar konstruksi ini berfungsi; jika Anda membutuhkan urutan yang berbeda, bungkus kueri dalam subkueri:
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