[英]sum() column for multiple queries of the same id and display to joined tables
我可以选择一列的总和并将其显示在与其连接的另一个表中吗?
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就能自动完成吗?
您只需要按原样联接表并在此处使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.