0

I want to write a query for cumulative sum in MYSQL. I have a foreign key in my table and I want to add their hours as a cumulative sum.

Table 1

id(not primary key)   Hours
1                       4
2                       4
1                       5

I have tried this query

select spent_hours := spent_hours + hours as spent 
from time 
join (select spent_hours := 0) s

I am getting this

id(not primary key)    hours    spent
1                       4        4
2                       4        8
1                       5        13

But I want this result:

id(not primary key)    Hours spent
1                       4    4
2                       4    4
1                       5    9
jpw
  • 44,361
  • 6
  • 66
  • 86
Jerry
  • 145
  • 2
  • 13

2 Answers2

1

Since you have an autoincrement field (let's assume for this case its called record_id) you can use this little trick to achieve what you want:

SELECT Main.id, Main.spentHours,
(
    SELECT SUM(spentHours) 
    FROM Table1 WHERE Table1.id = Main.id
    AND Table1.record_id >= Main.record_id
) as totalSpentHours
FROM Table1 Main
ORDER BY Main.record_id ASC

This will fetch the id, current spent hours, along using a subselect, all hours from the current ID and above for that user.

Aziz Saleh
  • 2,687
  • 1
  • 17
  • 27
0

You need additional an variable to keep track of the cumulative sum within each id:

select t.id, t.hours,
       (@h := if(@i = id, @h + spent_hours,
                 if(@i := id, spent_hours, spent_hours)
                )
       ) as spent
from time cross join
     (select @h := 0, @i := 0) params
order by id, ??;

Note: you need an additional column to specify the order for the cumulative sum (indicated by ?? in the order by clause. Remember that SQL tables represent unordered sets, so you need a column to explicitly represent ordering.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786