mysql - 如何使用sql获取同一个表中的列总和然后2个表之间的差异

标签 mysql

如何有两个表

1.doner_record-->

Id| doner_id|blood_group | units |status|
1 |       1       |A                    | 3        |0         |
2 |        3      |B                    | 2        |0         |
3 |        2      |A                    | 1        |0         |
4 |        1      |A                    | 2        |0         |

2.接受者

Id| name        |blood_group | units |status|
1 |       ayush  |A                    | 1        |0         |
2 |       akash  |B                    | 2        |0         |
3 |        Hari     |A                   | 1        |0         |
4 |        Ram    |A                   | 1        |0         |

如何使用sql获取血型库存

|blood_group | units |
|A                    | 3        |
|B                    | 0        |

最佳答案

对于库存血液单位,您需要从接受的单位总数中检查剩余的单位。

检查此查询可能会得到结果:

select blood_group,(ifnull(t1.unit,0) - ifnull(t2.unit,0)) as StockedUnit  from 
(select blood_group,sum(unit) unit from 
doner_record group by blood_group) t1
left outer join
(select blood_group,sum(unit) unit from 
acceptors group by blood_group) t2

on t1.blood_group = t2.blood_group

关于mysql - 如何使用sql获取同一个表中的列总和然后2个表之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48593542/

相关文章:

mysql - 新手 : unix bash, 嵌套 if 语句,循环结果来自 sql

php - Zend 如何以编程方式创建 mysql 表?

php - 您应该在 PHP 中缓存 MySQL 连接吗?

mysql - 处理多个 MySql 查询(删除和复制)

javascript - 如何将 Buffer 对象转换为 Node.js 中的文件?

android - 在listview android中对多行进行分组

mysql - 如何从另一个表的 2 个变量更新一个表?

mysql - 按名称排序未按预期工作 - MySQL

php - 在客户端计算还是在服务器上计算?

html - 如何为我的网站使用 session 变量进行 SQL 查询?