减去两列并在运行时求和结果

时间:2013-02-17 17:53:59

标签: mysql runtime sum

我在MySQL中有两个表,它们有很多数据。我想减去两列并显示生成列的总和...

这就是我所拥有的

CREATE TABLE fin_invoice(
id MEDIUMINT NOT NULL AUTO_INCREMENT,
invoice_no INT,
total INT,
PRIMARY KEY (id)
) ENGINE=MyISAM;
INSERT INTO fin_invoice (`id`, `invoice_no`, `total`) VALUES (NULL, '1000', '1000'),
(NULL, '1001', '2000'),(NULL, '1002', '3000'),(NULL, '1003', '1200'),(NULL, '1004',     '2000'),
(NULL, '1005',   '1202'),(NULL, '1006', '220');

和表二是

CREATE TABLE fin_money(
id MEDIUMINT NOT NULL AUTO_INCREMENT,
fk_invoice INT,
amount INT,
PRIMARY KEY (id)
) ENGINE=MyISAM;

INSERT INTO `fin_money` (`id`, `fk_invoice`, `amount`) VALUES (NULL, '1', '100'),
(NULL, '2', '200'),(NULL, '3', '300'),(NULL, '4', '500'),(NULL, '5', '600'),
(NULL, '6',   '800'),(NULL, '7', '50');

表二(fin_money)连接到table1(fin_invoice),外键为fk_invoice.so,关系为fin_invoice.id = fin_money.fk_invoice

我想得到这个

+----+-------------+--------+------+---------+
| id |  total      | amount | bal  | running |
+----+-------------+--------+------+---------+
|  1 |        1000 |    100 |  900 |     900 |
|  2 |        2000 |    200 | 1800 |    2700 |
|  3 |        3000 |    300 | 2700 |    5400 |
|  4 |        1200 |    500 |  700 |    6100 |
|  5 |        2000 |    600 | 1400 |    7500 |
|  6 |        1202 |    800 |  402 |    7902 |
|  7 |         220 |     50 |  170 |    8072 |
+----+-------------+--------+------+---------+

其中bal =总量和跑步是bal和前一个id的运行之和。比如900 + 0 = 900和1800 + 900 = 2700等等。

1 个答案:

答案 0 :(得分:3)

这应该使用局部变量来创建一个运行总计:

SELECT fi.id, 
  fi.total, 
  fm.amount,
  fi.total-fm.amount bal,
  @runTotal:=@runTotal+fi.total-fm.amount runTotal
FROM fin_invoice fi 
  JOIN fin_money fm ON fi.id = fm.fk_invoice
  JOIN (SELECT @runTotal:= 0) r;

这是SQL Fiddle

结果:

ID  TOTAL   AMOUNT  BAL    RUNTOTAL
1   1000    100     900    900
2   2000    200     1800   2700
3   3000    300     2700   5400
4   1200    500     700    6100
5   2000    600     1400   7500
6   1202    800     402    7902
7   220     50      170    8072