简体   繁体   English

从两个表中减去列

[英]Subtract columns from two tables

I have two tables from which I need to subtract two columns 我有两个表,我需要从中减去两列

My query for that: 我对此的查询:

SELECT
  `T1`.`Code`,
  (Sum(`T1`.`Qty`) - Sum(`T2`.`Qty`)) AS TotalQty
FROM
  `T1`
  LEFT JOIN `T2` ON `T1`.`Code` =
    `T2`.`Code`
GROUP BY
  `T1`.`Code`

This works fine if I have data in table T2, but if there is no data than I get null as result for TotalQty even if T1 are some records. 如果我在表T2中有数据,这很好用,但是,即使没有数据,即使T1是一些记录,我也得到null作为TotalQty的结果。 How to get correct calculation even there is no data in T2? 即使T2中没有数据,如何获得正确的计算?

Try this.. 尝试这个..

SELECT
  `T1`.`Code`,
  (IFNULL(Sum(`T1`.`Qty`),0) - IFNULL(Sum(`T2`.`Qty`),0)) AS TotalQty
FROM
  `T1`
  LEFT JOIN `T2` ON `T1`.`Code` =
    `T2`.`Code`
GROUP BY
  `T1`.`Code`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM