Search code examples
mysqldb2bigdatabiginsightsbigsql

MySQL issue with NULL values


I have a table with fields: country_code, short_name, currency_unit, a2010, a2011, a2012, a2013, a2014, a2015. a2010-a2015 fields are type of double.

How do I make a query which orders the results by average of fields a2010-a2015, keeping in mind that these fields might have NULL value?

I tried this code and it did not work (returns a mistake, which tells there is something wrong in ORDER BY part. mistake was saying something about coumn names and GROUP BY). The logic is: ORDER BY ((A)/(B)) where A - sum of not NULL fields and B - count of not NULL fields.

Any ideas?

(if important, the code is going to be used in BigInsights environment)

SELECT country_code, short_name, currency_unit, a2010, a2011, a2012, 
a2013, a2014, a2015
FROM my_schema.my_table
WHERE Indicator_Code = 'SE.PRM.TENR'
ORDER BY 
(
(
Coalesce(a2010,0) + Coalesce(a2011,0) + Coalesce(a2012,0)  
+Coalesce(a2013,0) + Coalesce(a2014,0) + Coalesce(a2015,0)
)
/
(
COUNT(Coalesce(a2010)) + COUNT(Coalesce(a2011)) + COUNT(Coalesce(a2012)) 
+ COUNT(Coalesce(a2013)) + COUNT(Coalesce(a2014)) + 
COUNT(Coalesce(a2015))
)
) DESC;

Solution

  • use MySQL ifnull

    IFNULL(expression_1,expression_2)
    

    in your query :-

    IFNULL(
    (
    COUNT(Coalesce(a2010)) + COUNT(Coalesce(a2011)) + COUNT(Coalesce(a2012)) 
    + COUNT(Coalesce(a2013)) + COUNT(Coalesce(a2014)) + 
    COUNT(Coalesce(a2015))
    ),
    1
    )