P粉2452767692023-08-23 09:47:13
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
非常重要,它確保順序與原始問題匹配,並且對於更複雜的變數使用(例如:偽ROW_NUMBER/RANK功能,MySQL不支援)可能會有更大的影響P粉0065406002023-08-23 00:13:27
如果效能是一個問題,你可以使用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;
這樣以連續的方式計算累積和 :)