我有下表:
+-------------+-------+-------+
| date | agent | hold |
+-------------+-------+-------+
| 2017-01-01 | A | 100 |
| 2017-01-01 | B | 200 |
| 2017-01-02 | C | 400 |
+-------------+-------+-------+
我添加运行总计的查询:
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
但是我在列rt中得到每行的总和(保持)。我做错了什么?
答案 0 :(得分:1)
使用建议的汇总或将agrregates移动到子查询并在主查询中执行运行总计。例如 给定
+------------+------------+---------+
| 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)