R_life_R
R_life_R

Reputation: 816

Running total MySQL showing the sum of row

I have the following table:

+-------------+-------+-------+
|    date     | agent |  hold |
+-------------+-------+-------+
| 2017-01-01  | A     |   100 |
| 2017-01-01  | B     |   200 |
| 2017-01-02  | C     |   400 |
+-------------+-------+-------+

My query to add a running total:

SET @runtot:=0;
SELECT
 date,
  SUM(CASE WHEN agent = 'A' THEN hold ELSE 0 END) AS A,
  SUM(CASE WHEN agent = 'B' THEN hold ELSE 0 END) AS B,
 SUM(CASE WHEN agent = 'C' THEN hold ELSE 0 END) AS C,
SUM(CASE WHEN agent = 'D' THEN hold ELSE 0 END) AS D,
sum(hold) as Total,
(@runtot := @runtot + sum(hold)) AS rt
FROM daily_results
group by date

But I get as running total in column rt the sum(hold) of each row. What am I doing wrong?

Upvotes: 0

Views: 51

Answers (1)

P.Salmon
P.Salmon

Reputation: 17615

Either use rollup as suggested or move the agrregates to a sub query and do the running total in the main query. for example Given

+------------+------------+---------+
| tanggal    | iddowntime | idshift |
+------------+------------+---------+
| 2017-10-03 | MOR01      |       1 |
| 2017-10-03 | NF001      |       2 |
| 2017-10-03 | MOR01      |       2 |
| 2017-10-02 | MOR01      |       2 |
| 2017-10-03 | NF001      |       2 |
| 2017-10-02 | MOR01      |       1 |
| 2017-10-02 | NF001      |       1 |
| 2017-10-02 | NF001      |       1 |
+------------+------------+---------+
8 rows in set (0.00 sec)

select s.*,
        @rt:=@rt + total RunningTotal
from
(
SELECT
  tanggal,
  SUM(CASE WHEN iddowntime = 'mor01' THEN idshift ELSE 0 END) AS A,
  SUM(CASE WHEN iddowntime = 'nf001' THEN idshift ELSE 0 END) AS B,
  #SUM(CASE WHEN agent = 'C' THEN hold ELSE 0 END) AS C,
  #SUM(CASE WHEN agent = 'D' THEN hold ELSE 0 END) AS D,
  sum(idshift) as Total
FROM trans_lhpdtdw
where iddowntime in('mor01','nf001')
group by tanggal 
) s
cross join
(select @rt:=0) rt

+------------+------+------+-------+--------------+
| tanggal    | A    | B    | Total | RunningTotal |
+------------+------+------+-------+--------------+
| 2017-10-02 |    3 |    2 |     5 |            5 |
| 2017-10-03 |    3 |    4 |     7 |           12 |
+------------+------+------+-------+--------------+
2 rows in set (0.01 sec)

Upvotes: 1

Related Questions