即使我过滤了结果,即使我在列上使用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 |
+-----------------+
答案 0 :(得分:1)
您的问题是ORDER BY
和LIMIT
子句在SUM
发生之后最后出现。您需要先在子查询中选择要求和的数据,然后对其求和:
SELECT SUM(stockinquantity) AS stockinquantity
FROM (SELECT stockinquantity
FROM tblmedstockin
WHERE medid = 1004
ORDER BY stockindate asc
LIMIT 2) t