如何在H2数据库中对不同表中的两列进行求和

时间:2017-09-08 11:54:01

标签: h2

我在数据库中有两个名为purchasesales的表 表格如下

purchases

----------------------------
ID  PRODUCT   QTY 
----------------------------
1   APPLE     100
2   BANANA    200
3   GRAPES    150
4   AVACADO   110

Sales

----------------------------
ID  PRODUCT   QTY 
----------------------------
1   APPLE     50
2   BANANA    200
3   GRAPES    100

在上面的表格中我有purchasesales我希望从purchases数量减去sales数量

并获得像这样的输出

Output
----------------------------
ID  PRODUCT   QTY 
----------------------------
1   APPLE     50
2   BANANA    0
3   GRAPES    50
4   AVACADO   110

我写了查询但没有工作

select id, product, (purchases.qty)-(sales.qty) from purchases left join sales on purchases.id=sales.id

2 个答案:

答案 0 :(得分:1)

<强>解决方案

SELECT purchases.id,purchases.product, (purchases.qty - IF (sales.qty IS NULL, 0, sales.qty)) as qty FROM pruchases LEFT JOIN sales ON purchases.product = sales.product

答案 1 :(得分:0)