I have two tables with a decimal value, using the following statement I can add them all up and get the total.
SELECT(
(SELECT SUM(total) from recruitment where quote_id = 1)
+
(SELECT SUM(cost) from cost WHERE quote_id = 1)
)AS total
But if either select reurns null then the the total is null so I tried using ISNULL to return a 0 rather than null like this:
SELECT(
(IFNULL(SELECT SUM(total) FROM recruitment WHERE quote_id = 1),0)
+
(IFNULL(SELECT SUM(cost) FROM cost WHERE quote_id = 1),0)
)AS total
This didn't work, so I was just wondering how is the best way to go about doing this?
Use COALESCE()
which returns its first non-null argument, and can replace the whole expression with a zero.
SELECT(
COALESCE((SELECT SUM(total) FROM recruitment WHERE quote_id = 1),0)
+
COALESCE((SELECT SUM(cost) FROM cost WHERE quote_id = 1),0)
)AS total
IFNULL()
should work the same way in this case - I suspect you may have had incorrect parentheses causing a syntax error.
/* Should work too. Make sure the inner SELECT is enclosed in () */
SELECT(
IFNULL((SELECT SUM(total) FROM recruitment WHERE quote_id = 1),0)
+
IFNULL((SELECT SUM(cost) FROM cost WHERE quote_id = 1),0)
)AS total
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With