Reputation: 2726
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. How to get correct calculation even there is no data in T2?
Upvotes: 0
Views: 3185
Reputation: 153
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`
Upvotes: 3