0

I sum up the rows of two columns in two tables i.e. something like this:

SUM( tableA.age ) + sum( tableB.age) as 'Total Ages'

But in some cases the result of table A is null while result of table B is not. In this case I get as a total result null although it is something like "NULL + 45" which is not null actually. Therefore I thought it would be a good idea to use the if clause of the sql syntax. But it does not work I get an error when trying to do the following:

IF SUM( tableA.age ) IS NULL THEN 0 ELSE  SUM( tableA.age ) END IF + IF SUM( tableB.age ) IS NULL THEN 0 ELSE  SUM( tableB.age ) END IF

How would I do that in a proper way?

4

3 に答える 3

1

Instead of the complex (and syntactically incorrect) IF statements, use COALESCE(), which returns its first non-null argument, and specify 0 as its second argument so it defaults to zero when the aggregate SUM() is null

COALESCE(SUM(tableA.age), 0) + COALESCE(SUM(tableB.age), 0)
于 2012-08-07T13:41:25.993 に答える
1

Simply use IFNULL() when you feel the field has NULL value.

 SUM(IFNULL(tableA.age,0) ) 

You can use this MYSQL function.

于 2012-08-07T14:00:39.123 に答える
0

Use IFNULL(column, 0) to convert the column value to zero:

SUM( IFNULL(tableA.age,0) ) + SUM( IFNULL(tableB.age,0) ) as 'Total Ages'
于 2012-08-07T13:42:22.307 に答える