森欄
2019-06-14 15:35:53
在MySQL中創(chuàng)建累積和列我有張桌子看起來(lái)像這樣:id count1 1002 503 10我想添加一個(gè)名為累加和的新列,因此表如下所示:id count cumulative_sum1 100 1002 50 1503 10 160是否有MySQL UPDATE語(yǔ)句可以很容易地做到這一點(diǎn)?做這件事最好的方法是什么?
3 回答

慕婉清6462132
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
set @csum := 0;update YourTableset cumulative_sum = (@csum := @csum + count)order by id;
cumulative_sum
set @csum := 0;select id, count, (@csum := @csum + count) as cumulative_sumfrom YourTableorder by id;

慕田峪9158850
TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
使用相關(guān)查詢:
SELECT t.id, t.count, (SELECT SUM(x.count) FROM TABLE x WHERE x.id <= t.id) AS cumulative_sum FROM TABLE tORDER BY t.id
使用MySQL變量:
SELECT t.id, t.count, @running_total := @running_total + t.count AS cumulative_sum FROM TABLE t JOIN (SELECT @running_total : = 0) rORDER BY t.id
這個(gè) JOIN (SELECT @running_total := 0) r
是交叉連接,并且允許在不需要單獨(dú)聲明的情況下進(jìn)行變量聲明。 SET
命令。 表化名, r
,對(duì)于任何子查詢/派生表/內(nèi)聯(lián)視圖,MySQL都需要
特定于MySQL;不能移植到其他數(shù)據(jù)庫(kù) 這個(gè) ORDER BY
很重要;它確保順序與OP匹配,并且對(duì)于更復(fù)雜的變量使用有更大的影響(IE:psuedo ROW_Number/RANK功能,MySQL缺乏這種功能)

精慕HU
TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊
SUM(col) OVER()
:
SELECT *, SUM(cnt) OVER(ORDER BY id) AS cumulative_sumFROM tab;
┌─────┬──────┬────────────────┐
│ id │ cnt │ cumulative_sum │
├─────┼──────┼────────────────┤
│ 1 │ 100 │ 100 │
│ 2 │ 50 │ 150 │
│ 3 │ 10 │ 160 │
└─────┴──────┴────────────────┘
添加回答
舉報(bào)
0/150
提交
取消