我可以选择一列的总和并将其显示在与其连接的另一个表中吗?
tblmedstockin
+--------------+-------+-----------------+-------------+----------------+
| medstockinid | medid | stockinquantity | stockindate | stockinexpdate |
+--------------+-------+-----------------+-------------+----------------+
| 1 | 1001 | 100 | 2019-01-29 | 2019-12-16 |
| 2 | 1001 | 100 | 2019-01-29 | 2019-12-16 |
| 3 | 1001 | 12 | 2019-01-29 | 2019-01-29 |
| 5 | 1004 | 4 | 2019-01-29 | 2019-01-29 |
| 6 | 1004 | 20 | 2019-01-30 | 2019-01-30 |
预期结果:
tblmedstock
+------------+-------+----------+-----------+-----------------+--------------+
| medstockid | medid | category | medname | stockinquantity | stockcritqty |
+------------+-------+----------+-----------+-----------------+--------------+
| 1001 | 1001 | Tablet | Losartan | 212 | 100 |
| 1004 | 1004 | Tablet | Metformin | 24 | 100 |
+------------+-------+----------+-----------+-----------------+--------------+
我想从tblmedstockin中求和(库存量)多行并将其显示为tblmedstock上的一列。
尝试过此代码,但必须手动更改每个查询的ID:
select a.medstockid, c.medid, c.category, c.medname, (select sum(stockinquantity)from tblmedstockin where medid = 1001) as stockinquantity, a.stockcritqty from tblmedstock a inner join tblmedstockin b on a.medstockinid = b.medstockinid inner join tblmedicine c on a.medid = c.medid where a.medid = 1001
-> union
-> select a.medstockid, c.medid, c.category, c.medname, (select sum(stockinquantity)from tblmedstockin where medid = 1004) as stockinquantity, a.stockcritqty from tblmedstock a inner join tblmedstockin b on a.medstockinid = b.medstockinid inner join tblmedicine c on a.medid = c.medid where a.medid = 1004;
可以将其自动无需手动设置id完成?
答案 0 :(得分:0)
您只需要按原样联接表并在此处使用GROUP BY(在此处对表关系进行一些假设):
select a.medstockid, c.medid, c.category, c.medname, sum(b.stockinquantity), a.stockcritqty
from tblmedstock a
Removed since this doesn't appear to be used in this query*/
inner join tblmedstockin b on a.medstockinid = b.medstockinid*/
inner join tblmedicine c on a.medid = c.medid
WHERE a.medid in (1001,1004)
GROUP BY a.medstockid, c.medid, c.category, c.medname, a.stockcritqty