对选定行的值求和

时间:2019-02-09 01:56:05

标签: mysql mysql-workbench

即使我过滤了结果,即使我在列上使用sum(),它仍然会汇总所有值。

这里是我的桌子:

mysql> select * from tblmedstockin where  medid = 1004;
+--------------+-------+-----------------+-------------+----------------+
| medstockinid | medid | stockinquantity | stockindate | stockinexpdate |
+--------------+-------+-----------------+-------------+----------------+
|            5 |  1004 |             147 | 2019-01-29  | 2019-01-29     |
|            6 |  1004 |              20 | 2019-01-30  | 2019-01-30     |
|           13 |  1004 |              45 | 2019-02-07  | 2019-02-07     |
+--------------+-------+-----------------+-------------+----------------+


mysql> select stockinquantity as stockinquantity from tblmedstockin where  medid = 1004 order by stockindate asc;
+-----------------+
| stockinquantity |
+-----------------+
|             147 |
|              20 |
|              45 |
+-----------------+

我只想对前两列进行求和

mysql> select stockinquantity as stockinquantity from tblmedstockin where  medid = 1004 order by stockindate asc limit 2;
+-----------------+
| stockinquantity |
+-----------------+
|             147 |
|              20 |
+-----------------+

我得到的结果:

mysql> select sum(stockinquantity) as stockinquantity from tblmedstockin where medid = '1004' order by stockindate asc limit 2;
+-----------------+
| stockinquantity |
+-----------------+
|             212 |
+-----------------+

预期结果应为:

+-----------------+
| stockinquantity |
+-----------------+
|             167 |
+-----------------+

1 个答案:

答案 0 :(得分:1)

您的问题是ORDER BYLIMIT子句在SUM发生之后最后出现。您需要先在子查询中选择要求和的数据,然后对其求和:

SELECT SUM(stockinquantity) AS stockinquantity 
FROM (SELECT stockinquantity
      FROM tblmedstockin 
      WHERE medid = 1004
      ORDER BY stockindate asc
      LIMIT 2) t