我有一个看起来像这样的表:
id count
1 100
2 50
3 10
我想添加一个名为cumulative_sum的新列,因此表格如下所示:
id count cumulative_sum
1 100 100
2 50 150
3 10 160
是否有可以轻松完成此操作的MySQL更新语句?实现这一目标的最佳方法是什么?
答案 0 :(得分:91)
SELECT t.id,
t.count,
(SELECT SUM(x.count)
FROM TABLE x
WHERE x.id <= t.id) AS cumulative_sum
FROM TABLE t
ORDER BY t.id
SELECT t.id,
t.count,
@running_total := @running_total + t.count AS cumulative_sum
FROM TABLE t
JOIN (SELECT @running_total := 0) r
ORDER BY t.id
注意:
JOIN (SELECT @running_total := 0) r
是一个交叉连接,允许变量声明而无需单独的SET
命令。 r
注意事项:
ORDER BY
很重要;它确保顺序与OP匹配,并且可以对更复杂的变量使用产生更大的影响(IE:psuedo ROW_NUMBER / RANK功能,MySQL缺乏)答案 1 :(得分:80)
如果性能有问题,可以使用MySQL变量:
set @csum := 0;
update YourTable
set cumulative_sum = (@csum := @csum + count)
order by id;
或者,您可以删除cumulative_sum
列并在每个查询中计算它:
set @csum := 0;
select id, count, (@csum := @csum + count) as cumulative_sum
from YourTable
order by id;
以跑步的方式计算运行总和:)
答案 2 :(得分:5)
MySQL 8.0 / MariaDB支持窗口SUM(col) OVER()
:
SELECT *, SUM(cnt) OVER(ORDER BY id) AS cumulative_sum
FROM tab;
输出:
┌─────┬──────┬────────────────┐
│ id │ cnt │ cumulative_sum │
├─────┼──────┼────────────────┤
│ 1 │ 100 │ 100 │
│ 2 │ 50 │ 150 │
│ 3 │ 10 │ 160 │
└─────┴──────┴────────────────┘
答案 3 :(得分:3)
UPDATE t
SET cumulative_sum = (
SELECT SUM(x.count)
FROM t x
WHERE x.id <= t.id
)
答案 4 :(得分:2)
示例查询
SET @runtot:=0;
SELECT
q1.d,
q1.c,
(@runtot := @runtot + q1.c) AS rt
FROM
(SELECT
DAYOFYEAR(date) AS d,
COUNT(*) AS c
FROM orders
WHERE hasPaid > 0
GROUP BY d
ORDER BY d) AS q1
答案 5 :(得分:2)
select Id, Count, @total := @total + Count as cumulative_sum
from YourTable, (Select @total := 0) as total ;
答案 6 :(得分:1)
您还可以创建一个触发器,在每次插入之前计算总和
delimiter |
CREATE TRIGGER calCumluativeSum BEFORE INSERT ON someTable
FOR EACH ROW BEGIN
SET cumulative_sum = (
SELECT SUM(x.count)
FROM someTable x
WHERE x.id <= NEW.id
)
set NEW.cumulative_sum = cumulative_sum;
END;
|
我没有测试过这个
答案 7 :(得分:0)
从tableName中选择id,count,sum(count)over(按计数desc排序)作为累积总和;
我在count列上使用了sum合计函数,然后使用了over子句。它分别汇总每一行。第一行将是100。第二行将是100 + 50。第三行是100 + 50 + 10,依此类推。因此,基本上每一行都是它与之前所有行的总和,最后一行是所有行的总和。因此,查看此行的方式是每一行是ID小于或等于自身的数量之和。
答案 8 :(得分:0)
select t1.id, t1.count, SUM(t2.count) cumulative_sum
from table t1
join table t2 on t1.id >= t2.id
group by t1.id, t1.count
分步操作:
1-给出下表:
select *
from table t1
order by t1.id;
id | count
1 | 11
2 | 12
3 | 13
2-按组获取信息
select *
from table t1
join table t2 on t1.id >= t2.id
order by t1.id, t2.id;
id | count | id | count
1 | 11 | 1 | 11
2 | 12 | 1 | 11
2 | 12 | 2 | 12
3 | 13 | 1 | 11
3 | 13 | 2 | 12
3 | 13 | 3 | 13
3-第3步:按t1.id组总和
select t1.id, t1.count, SUM(t2.count) cumulative_sum
from table t1
join table t2 on t1.id >= t2.id
group by t1.id, t1.count;
id | count | cumulative_sum
1 | 11 | 11
2 | 12 | 23
3 | 13 | 36