有这样的原始表:
X1 X2
-----------------------
2 453
2 120
2 101
2 89
3 111
3 421
3 219
-----------------------
根据X1字段进行累加,我要循环累加后变成下面的表
X1 X2
-----------------------
2 453
2 573
2 674
2 763
3 111
3 532
3 751
-----------------------
CREATE TABLE test
(
Id INT NOT NULL AUTO_INCREMENT,
X1 INT NOT NULL,
X2 INT NOT NULL,
PRIMARY KEY(`Id`)
)
INSERT INTO test(X1,X2) VALUES(2,453),(2,120),(2,101),(2,89),(3,111),(3,421),(3,219)
SELECT * FROM test
SELECT X1,(SELECT SUM(X2) FROM test WHERE X1=A.X1 AND Id<=A.Id)
FROM test A
-----------------------
X1 (SELECT SUM(X2) from test where X1=A.X1 and Id<=A.Id)
2 453
2 573
2 674
2 763
3 111
3 532
3 751