0

我在 MySQL 中有一个包含大量数据的表。我想显示生成列的总和...

我减去两列,我想显示结果的总和。这是我所拥有的

 CREATE TABLE amounts(
id MEDIUMINT NOT NULL AUTO_INCREMENT,
bank_amount INT,
amount INT,
PRIMARY KEY (id)
) ENGINE=MyISAM;
INSERT INTO `amounts` (`id`, `bank_amount`, `amount`) VALUES (NULL, '1000', '100'),
(NULL, '2000', '200'),(NULL, '3000', '300'),(NULL, '1200', '500'),(NULL, '2000', '600'),
(NULL, '1202',   '800'),(NULL, '220', '50');

我有这个查询

SELECT bank_amount,amount,(bank_amount-amount) as bal from amounts where ......

上面的查询会给我这个结果

bank_amount 金额 bal

1000 100 900

2000 200 1800

3000 300 2700

等等

现在我想显示 bal 的 SUM 也像 900+1800+2700

4

2 回答 2

1

你是这个意思吗?

SELECT x.*
      , x.bank_amount-x.amount bal
      , SUM(y.bank_amount-y.amount) running
   FROM amounts x
   JOIN amounts y
     ON y.id <= x.id
  GROUP
     BY id;
 +----+-------------+--------+------+---------+
 | id | bank_amount | 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 |
 +----+-------------+--------+------+---------+
于 2013-02-17T10:18:19.403 回答
0

你在寻找

SELECT
    A.id,
    A.bank_amount,
    A.amount,
    (A.bank_amount - A.amount) as bal,
    T.Total_bal
FROM amounts A
    JOIN 
      (
          SELECT Id, SUM(bank_amount-amount) Total_bal
          FROM amounts
          GROUP BY Id
      ) T
      ON A.Id = T.Id

?

于 2013-02-17T09:43:11.123 回答